[java] Java: getMinutes and getHours

How do you get Hours and Minutes since Date.getHours and Date.getMinutes got deprecated? The examples that I found on Google search used the deprecated methods.

This question is related to java date time

The answer is


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!

java.time

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())

tl;dr

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 ) ;

Specify time zone

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.

Hour-minute

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).

java.time types

Table of types of date-time classes in modern java.time versus legacy.


About java.time

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object