Getting Current Date and Time in Java
This tutorial shows how to get the current date and time in Java. The standard Java classes we can use are java.util.Date
, java.util.Calendar
and the new java 8 java.time.LocalDateTime
and java.time.ZonedDateTime
. You could also use external libraries such as org.joda.time.DateTime
.
java.util.Date
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
java.util.Calendar
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
java.time.LocalDateTime
DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(dateTimeFormat.format(localDateTime));
org.joda.time.DateTime
DateTimeFormatter dateFormat = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
DateTime now = new DateTime();
System.out.println(dateFormat.print(now));
Current Date/Time in Java
package com.memorynotfound.birthdate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
public class CalculateBirthDatePlainJava {
public static void main(String... args){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(dateTimeFormat.format(localDateTime));
}
}
2016/10/27 10:06:44
2016/10/27 10:06:44
2016/10/27 10:06:44
References
- Date JavaDoc
- Calendar JavaDoc
- SimpleDateFormat JavaDoc
- LocaleDateTime JavaDoc
- DateTimeFormatter JavaDoc
- Joda DateTime JavaDoc
Download
Download it – correct-ways-getting-current-date-time-java