Try Calender. Use getInstance to get a Calender-Object. Then use setTime to set the required Date. Now you can use get(int field) with the appropriate constant like HOUR_OF_DAY or so to read the values you need.
http://java.sun.com/javase/6/docs/api/java/util/Calendar.html
public static LocalTime time() {
LocalTime ldt = java.time.LocalTime.now();
ldt = ldt.truncatedTo(ChronoUnit.MINUTES);
System.out.println(ldt);
return ldt;
}
This works for me
From the Javadoc for Date.getHours
As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY)
So use
Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);
and the equivalent for getMinutes.
import java.util.*
You can gethour and minute using calendar and formatter class. Calendar cal = Calendar.getInstance()
and Formatter fmt=new Formatter()
and set a format for display hour and minute fmt.format("%tl:%M",cal,cal)
and print System.out.println(fmt)
output shows like 10:12
Try using Joda Time instead of standard java.util.Date classes. Joda Time library has much better API for handling dates.
DateTime dt = new DateTime(); // current time
int month = dt.getMonth(); // gets the current month
int hours = dt.getHourOfDay(); // gets hour of day
See this question for pros and cons of using Joda Time library.
Joda Time may also be included to some future version of Java as a standard component, see JSR-310.
If you must use traditional java.util.Date and java.util.Calendar classes, see their JavaDoc's for help (java.util.Calendar and java.util.Date).
You can use the traditional classes like this to fetch fields from given Date instance.
Date date = new Date(); // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date); // assigns calendar to given date
calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
calendar.get(Calendar.HOUR); // gets hour in 12h format
calendar.get(Calendar.MONTH); // gets month number, NOTE this is zero based!
While I am a fan of Joda-Time, Java 8 introduces the java.time package which is finally a worthwhile Java standard solution! Read this article, Java SE 8 Date and Time, for a good amount of information on java.time outside of hours and minutes.
In particular, look at the LocalDateTime
class.
Hours and minutes:
LocalDateTime.now().getHour();
LocalDateTime.now().getMinute();
First, import java.util.Calendar
Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));
int hr=Time.valueOf(LocalTime.now()).getHours();
int minutes=Time.valueOf(LocalTime.now()).getMinutes();
These functions will return int values in hours and minutes.
One more way of getting minutes and hours is by using SimpleDateFormat.
SimpleDateFormat formatMinutes = new SimpleDateFormat("mm")
String getMinutes = formatMinutes.format(new Date())
SimpleDateFormat formatHours = new SimpleDateFormat("HH")
String getHours = formatHours.format(new Date())
ZonedDateTime.now().getHour()
… or …
LocalTime.now().getHour()
ZonedDateTime
The Answer by J.D. is good but not optimal. That Answer uses the LocalDateTime
class. Lacking any concept of time zone or offset-from-UTC, that class cannot represent a moment.
Better to use ZonedDateTime
.
ZoneId z = ZoneID.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
If you omit the ZoneId
argument, one is applied implicitly at runtime using the JVM’s current default time zone.
So this:
ZonedDateTime.now()
…is the same as this:
ZonedDateTime.now( ZoneId.systemDefault() )
Better to be explicit, passing your desired/expected time zone. The default can change at any moment during runtime.
If critical, confirm the time zone with the user.
Interrogate the ZonedDateTime
for the hour and minute.
int hour = zdt.getHour() ;
int minute = zdt.getMinute() ;
LocalTime
If you want just the time-of-day without the time zone, extract LocalTime
.
LocalTime lt = zdt.toLocalTime() ;
Or skip ZonedDateTime
entirely, going directly to LocalTime
.
LocalTime lt = LocalTime.now( z ) ; // Capture the current time-of-day as seen in the wall-clock time used by the people of a particular region (a time zone).
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
I would recommend looking ad joda time. http://www.joda.org/joda-time/
I was afraid of adding another library to my thick project, but it's just easy and fast and smart and awesome. Plus, it plays nice with existing code, to some extent.
While I wouldn't recommend doing so, I think it's worth pointing out that although many methods on java.util.Date have been deprecated, they do still work. In trivial situations, it may be OK to use them. Also, java.util.Calendar is pretty slow, so getMonth and getYear on Date might be be usefully quicker.
Source: Stackoverflow.com