Java provides many useful ways to get current date time, current date, or current time using newly introduced LocalDate
, LocalDateTime
and ZonedDateTime
classes in Java 8 Date/Time API classes.
In this article, I will show you how to get current –
- Date
- Date in a specific format
- Time
- Time in 12-hour format
- 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));
}
}