Extracting date, hour and minute from Instant.now() generated date

Gandalf picture Gandalf · Mar 19, 2018 · Viewed 15.4k times · Source

I have this code that generates a date and time,

ZoneId z = ZoneId.of( "Africa/Nairobi" );

Instant instant = Instant.now();

ZonedDateTime zdt = instant.atZone(z);

return zdt.toString();

//2018-03-19T09:03:22.858+03:00[Africa/Nairobi]

Is there a lib like chrono - https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoField.html field that I can use to get the date, hour and minute?

Chrono fields does not extract the complete date.

Answer

Ole V.V. picture Ole V.V. · Mar 19, 2018

Since you seem to have been confused about how to get the date from your ZonedDateTime, I should like to supplement Claudiu Guja’a good and correct answer.

    ZoneId z = ZoneId.of("Africa/Nairobi");
    ZonedDateTime zdt = ZonedDateTime.now(z);
    System.out.println("Date         " + zdt.toLocalDate());
    System.out.println("Year         " + zdt.getYear());
    System.out.println("Month        " + zdt.getMonth());
    System.out.println("Day of month " + zdt.getDayOfMonth());

This just printed:

Date         2018-03-19
Year         2018
Month        MARCH
Day of month 19

Please check the documentation for more methods including getMonthValue for the number of the month (1 through 12). I include a link at the bottom. Since ZonedDateTime class has a now method, you don’t need Instant.now() first.

If you wanted an old-fashioned java.util.Date object — first answer is: don’t. The modern API you are already using is much nicer to work with. Only if you need a Date for some legacy API that you cannot change or don’t want to change just now, get an Instant and convert it:

    Instant instant = Instant.now();
    Date oldfashionedDateObject = Date.from(instant);
    System.out.println("Old-fashioned java.util.Date " + oldfashionedDateObject);

This printed:

Old-fashioned java.util.Date Mon Mar 19 12:00:05 CET 2018

Even though it says CET for Central European Time in the string, the Date does not contain a time zone (this confuses many). Only its toString method (called implicitly when I append the Date to a String) grabs the JVM’s time zone setting and uses it for generating the String while the Date stays unaffected.

In the special case where you just want a Date representing the date-time now, again, it’s ill-advised unless you have a very specific need, it’s very simple:

    Date oldfashionedDateObject = new Date();

The result is the same as above.

Links