Get Current Date and Time – Java 8 Examples

Java provides many useful ways to get current date timecurrent date, or current time using newly introduced LocalDateLocalDateTime and ZonedDateTime classes in Java 8 Date/Time API classes.

In this article, I will show you how to get current –

  1. Date
  2. Date in a specific format
  3. Time
  4. Time in 12-hour format
  5. Date and Time

1. Get Current Date in Java


Below Java code shows you how to get current date –

package com.kodehelp.java8;

import java.time.LocalDate;

public class CurrentDateExample {

    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now();
        System.out.println("Current Date: "+localDate);
    }
    
}

2. Get the Current Date in a specific format in Java


Below Java code shows you how to get current date in specific format –

package com.kodehelp.java8;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class CurrentDateExample {

    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        System.out.println("Current Date: "+formatter.format(localDate));
    }
    
}

3. Get Current Time in Java


Below Java code shows you how to get current time –

package com.kodehelp.java8;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class CurrentTimeExample {
    public static void main(String[] args) {
        
        LocalTime localTime = LocalTime.now();
        System.out.println("Current Time: "+localTime);

    }
}

4. Get Current Time in 12 hour format in Java


Below Java code shows you how to get current time in 12 hour format –

package com.kodehelp.java8;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class CurrentTimeExample {
    public static void main(String[] args) {

        LocalTime localTime = LocalTime.now();
        System.out.println("Current Time: "+localTime);

        // Pattern 
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("hh:mm:ss a");
        System.out.println("Time in 12 Hour format - " + localTime.format(pattern));

    }
}

5. Get Current DateTime in Java


Below Java code shows you how to get current DateTime –

package com.kodehelp.java8;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class CurrentDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("Current Date and Time: "+currentDateTime);

        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("uuuu-MM-dd hh:mm:ss a");
        System.out.println("Date Time in 12 Hour format - " + currentDateTime.format(pattern));
    }
}
References:
  1. Date JavaDoc
  2. LocalDateTime JavaDoc
  3. LocalDate JavaDoc
  4. DateTimeFormatter JavaDoc