Java ZonedDateTime now() and of() Method Example

ZonedDateTime class provides below APIs to create the current and specific date-time object with zone information as follows.
  • static ZonedDateTime now() - Obtains the current date-time from the system clock in the default time-zone.
  • static ZonedDateTime now(Clock clock) - Obtains the current date-time from the specified clock.
  • static ZonedDateTime now(ZoneId zone) - Obtains the current date-time from the system clock in the specified time-zone.
  • static ZonedDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneId zone) - Obtains an instance of ZonedDateTime from a year, month, day, hour, minute, second, nanosecond and time-zone.
  • static ZonedDateTime of(LocalDate date, LocalTime time, ZoneId zone) - Obtains an instance of ZonedDateTime from a local date and time.
  • static ZonedDateTime of(LocalDateTime localDateTime, ZoneId zone) - Obtains an instance of ZonedDateTime from a local date-time.

Java ZonedDateTime now() and of() Method Example

import java.time.Clock;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Program to demonstrate ZonedDateTime Class APIs.
 * @author javaguides.net
 *
 */
public class ZonedDateTimeExample {
 
    public static void main(String[] args) {
        createZonedDateTime();
    }
    private static void createZonedDateTime() {
        // Current date time
        ZonedDateTime dateTime1 = ZonedDateTime.now();
        System.out.println(dateTime1);

        // Current date time from specified time-zone
        ZonedDateTime dateTime2 = ZonedDateTime.now(ZoneId.of("UTC"));
        System.out.println(dateTime2);

        // Current date time from specified clock
        ZonedDateTime dateTime3 = ZonedDateTime.now(Clock.systemDefaultZone());
        System.out.println(dateTime3);

        // Current zoned date time from LocalDateTime
        ZonedDateTime dateTime4 = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("GMT"));
        System.out.println(dateTime4);

        // Specific zoned date time from LocalDateTime
        ZonedDateTime dateTime5 = ZonedDateTime.of(LocalDateTime.of(2017, 05, 12, 05, 45), ZoneId.of("Europe/London"));
        System.out.println(dateTime5);
     }
}
Output:
2018-08-11T11:15:37.717+05:30[Asia/Calcutta]
2018-08-11T05:45:37.718Z[UTC]
2018-08-11T11:15:37.718+05:30[Asia/Calcutta]
2018-08-11T11:15:37.718Z[GMT]
2017-05-12T05:45+01:00[Europe/London]

Reference


Comments