Java: getMinutes and getHours

JavaDateTime

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

Try using http://www.joda.org/joda-time/">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 https://stackoverflow.com/questions/589870/should-i-use-java-date-and-time-classes-or-go-with-a-3rd-party-library-like-joda">question</a> 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 http://jcp.org/en/jsr/detail?id=310">JSR-310</a>;.


If you must use traditional java.util.Date and java.util.Calendar classes, see their JavaDoc's for help (http://java.sun.com/javase/6/docs/api/java/util/Calendar.html">java.util.Calendar</a> and http://java.sun.com/javase/6/docs/api/java/util/Date.html">java.util.Date</a>;).

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!

Solution 2 - Java

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.

Solution 3 - Java

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

Solution 4 - Java

First, import java.util.Calendar

Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));

Solution 5 - Java

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

https://i.stack.imgur.com/MZe55.png" alt="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.

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

int hr=Time.valueOf(LocalTime.now()).getHours();
int minutes=Time.valueOf(LocalTime.now()).getMinutes();

These functions will return int values in hours and minutes.

Solution 9 - Java

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.

Solution 10 - Java

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

Solution 11 - Java

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.

Solution 12 - Java

  • Get hour from Date variable (yourdate):
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(yourdate);
    int hours = calendar.get(Calendar.HOUR_OF_DAY);
    int minutes = calendar.get(Calendar.MINUTE);
    int seconds = calendar.get(Calendar.SECOND);

Solution 13 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JavaJuha SyrjäläView Answer on Stackoverflow
Solution 2 - JavaMarkView Answer on Stackoverflow
Solution 3 - JavaJ.D.View Answer on Stackoverflow
Solution 4 - JavaJamesView Answer on Stackoverflow
Solution 5 - JavaBasil BourqueView Answer on Stackoverflow
Solution 6 - JavaTobias LangnerView Answer on Stackoverflow
Solution 7 - JavaPakaView Answer on Stackoverflow
Solution 8 - JavaNouran El KassasView Answer on Stackoverflow
Solution 9 - JavaalamarView Answer on Stackoverflow
Solution 10 - JavaHueyView Answer on Stackoverflow
Solution 11 - JavaskaffmanView Answer on Stackoverflow
Solution 12 - JavaSức Mạnh Niềm TinView Answer on Stackoverflow
Solution 13 - JavaBenjaminView Answer on Stackoverflow