Java – Get current date / time using various date classes

In this post, we can discuss how to get current date and time in Java.
These are some of the main new date classes that were introduced in Java 8.

  • Instant represents date and time in UTC.
  • LocalDate represents date.
  • LocalTime represents time.
  • LocalDateTime represents date and time without time zone. 
  • OffsetDateTime represents date and time with time zone offset. 
  • ZonedDateTime represents date and time with time zone information. 

now() method can be used to find the current date and/or time in all of these classes.
Default system time zone is used when now() method is called for LocalDateTime, LocalDate, and LocalTime classes.

Example:

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;

class DateTimeExample
{
    public static void main ( String[] args )
    {
        System.out.println( “Instant: ” + Instant.now() );
        System.out.println( “LocalDate: ” + LocalDate.now() );
        System.out.println( “LocalTime: ” + LocalTime.now() );
        System.out.println( “LocalDateTime: ” + LocalDateTime.now() );
        System.out.println( “OffsetDateTime (Default): ” + OffsetDateTime.now() );
        System.out.println( “OffsetDateTime (New_York): ” + OffsetDateTime.now( ZoneId.of( “America/New_York” ) ) );
        System.out.println( “ZonedDateTime (Default): ” + ZonedDateTime.now() );
        System.out.println( “ZonedDateTime (New_York): ” + ZonedDateTime.now( ZoneId.of( “America/New_York” ) ) );
    }
}

Output:

Instant: 2021-01-02T16:00:50.337Z
LocalDate: 2021-01-02
LocalTime: 21:30:50.525
LocalDateTime: 2021-01-02T21:30:50.525
OffsetDateTime (Default): 2021-01-02T21:30:50.525+05:30
OffsetDateTime (New_York): 2021-01-02T11:00:50.-05:00
ZonedDateTime (Default): 2021-01-02T21:30:50.525+05:30[Asia/Calcutta]|
ZonedDateTime (New_York): 2021-01-02T11:00:50.525-05:00[America/New_York]

If ZoneId is not specified, application/JVM time zone is used for OffsetDateTime and ZonedDateTime.
In these examples the default application time zone is ‘Asia/Calcutta’, and no formatting is applied here.

Leave a Comment

Your email address will not be published. Required fields are marked *