Java getHours(), getMinutes() and getSeconds()
Asked Answered
Z

4

85

As I know getHours(), getMinutes() and getSeconds() are all deprecated in Java and they are replaced with Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND.

These will in fact return the hour, minute and second for that particular moment. However, I would want to retrieved the hours and minutes from a Date variable. For instance,

say the time retrieved from database is

time = Thu Jan 01 09:12:18 CET 1970;

int hours = time.getHours();
int minutes = time.getMinutes();
int seconds = time.getSeconds();

By retrieving the hours, minutes, and seconds, I get

hours = 9
minutes = 12
seconds = 18

So, how do I use Calendar for this function? Although the getHours() has been deprecated but it still worked. I would still like to know if there is an alternative to this.

Zootoxin answered 16/11, 2011 at 10:30 Comment(1)
In modern Java, the terribly flawed date-time classes such as Calendar have been supplanted by the modern java.time classes defined in JSR 310.Backbreaker
G
184

Try this:

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

Edit:

hours, minutes, seconds

above will be the hours, minutes and seconds after converting yourdate to System Timezone!

Gabelle answered 16/11, 2011 at 11:8 Comment(1)
Also, if you need to set timezone, add TimeZone tz = TimeZone.getTimeZone("UTC"); // ... init calendar calendar.setTimeZone(tz); <code>Blondell
E
35

Java 8

    System.out.println(LocalDateTime.now().getHour());       // 7
    System.out.println(LocalDateTime.now().getMinute());     // 45
    System.out.println(LocalDateTime.now().getSecond());     // 32

Calendar

System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));  // 7 
System.out.println(Calendar.getInstance().get(Calendar.MINUTE));       // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND));       // 32

Joda Time

    System.out.println(new DateTime().getHourOfDay());      // 7
    System.out.println(new DateTime().getMinuteOfHour());   // 45
    System.out.println(new DateTime().getSecondOfMinute()); // 32

Formatted

Java 8

    // 07:48:55.056
    System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
    // 7:48:55
    System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());

    // 07:48:55
    System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));

    // 074855
    System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));

    // 07:48:55 
    System.out.println(new Date().toString().substring(11, 20));
Eruption answered 28/9, 2015 at 15:26 Comment(3)
V useful rundown: those are probably the most common sets of date/time systems today.Faxan
But it displayed, hours and minutes in single digit. Is it possible show two digitTestee
I cannot imagine a scenario where calling LocalDateTime.now is optimal. That class cannot represent a moment as it lacks the context of a time zone or offset-from-UTC. Use ZonedDateTime.now instead.Backbreaker
E
9

For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:

long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));

This will print:

Duration: 1:23:45.678

Electromechanical answered 23/1, 2013 at 10:11 Comment(2)
wow. just how impossible can date manipulation be made in java.Faxan
This is nonsense, and it tries to answer a different question from the one asked. Also for a time difference, since Java 8 you should use the Duration class. Except for method names being a bit funny, it behaves nicely and the way you would expect. Neither Date nor SimpleDateFormat were ever designed to work for a time difference. They also had severe design problems and have been outdated the last 10 years. So don’t use them. Ever.Mut
B
2

tl;dr

ZonedDateTime.now().getHour()

ZonedDateTime

all deprecated in Java and they are replaced with Calendar.

Update: Now the Calendar class has been supplanted by ZonedDateTime class in the java.time classes. The modern java.time classes have supplanted the terribly flawed legacy classes such as Calendar as of JSR 310.

Use ZonedDateTime to represent a moment as seen through the clock and calendar used by the people of a particular time zone. Specify the time zone as a ZoneId object.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;  // Capture the current moment as seen in a particular time zone.

If handed a Calendar object, cast to its likely subclass GregorianCalendar, then convert from legacy class to modern class.

GregorianCalendar gregCal = ( GregorianCalendar ) myCalendar ;  // Test with `instanceof` if not certain. 
ZonedDateTime zdt = gregCal.toZonedDateTime() ;

You asked:

getHours(), getMinutes() and getSeconds()

The ZonedDateTime class has equivalent methods.

int hour = zdt.getHour() ;
int minute = zdt.getMinute() ;
int second = zdt.getSecond() ;
int nano = zdt.getNano() ;  // The fraction of a second, as a count of nanoseconds ( zero to a billion ). 
Backbreaker answered 24/2 at 8:17 Comment(1)
I strongly suggest to use this answer for your production code. The legacy java.util date-time API was flawed and error-prone.Adlare

© 2022 - 2024 — McMap. All rights reserved.