Java 8 – Get Current Date and Time

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

Get Current Date in Java

Below Java code shows you how to get current date –

package com.codehelp.java8;

import java.time.LocalDate;

public class CurrentDateExample {

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

Get Current Date in specific format in Java

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

package com.codehelp.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));
    }
    
}

Get Current Time in Java

Below Java code shows you how to get current time

package com.codehelp.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);

    }
}

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

    }
}

Get Current Date Time in Java

package com.codehelp.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

 

 

 

Please Post Your Comments & Reviews

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.