In Java, there are different ways to get the current date and time. You can get the current date and time through the following classes:
- Date represents a specific instant in time, with millisecond precision.
- Calendar is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields.
- LocalDate represents date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.
- LocalDateTime represents date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.
- ZonedDateTime represents date-time with a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00 Europe/Paris.
Here are some examples to get the current date time using the classes mentioned above.
For Java 8 and onward
For Java 8 and onward, it is recommended to use the new Date and Time APIs that are part of java.time
package.
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class DateTime8Current { public static void main(String[] args) { LocalDate localDate = LocalDate.now(); System.out.println(localDate.toString()); LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime.toString()); ZonedDateTime zonedDateTime = ZonedDateTime.now(); System.out.println(zonedDateTime.toString()); // Convert current date time to different formats than ISO-8601. // ************************************************************** System.out.println( localDate.format(DateTimeFormatter.ofPattern("E, dd MMMM yyyy"))); System.out.println( localDateTime.format(DateTimeFormatter.ofPattern("yyyy/MM/dd hh:mm:ss a"))); System.out.println( zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss z"))); } }
Output
2019-11-17 2019-11-17T09:45:34.186370 2019-11-17T09:45:34.186656-05:00[America/Toronto] Sun, 17 November 2019 2019/11/17 09:45:34 PM 2019/11/17 09:45:34 EST
For Java 7 and below
For Java 7 and below, you can use Date and Calendar classes.
import java.util.Date; import java.util.Calendar; import java.text.SimpleDateFormat; public class DateTime7Current { public static void main(String[] args) { // Using Date class. Date date = new Date(); System.out.println(date.toString()); // Using Calendar class. // SimpleDateFormat is used because // Calendar.toString() outputs more data than needed. Calendar calendar = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); System.out.println(sdf.format(calendar.getTime())); } }
Output
Sun Nov 17 09:47:55 EST 2019 2019/11/17 09:47:55
Github
- For Java 8 and onward, use https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/time/DateTime8Current.java.
- For Java 7 and below, use https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/time/DateTime7Current.java.