In this example we will show four different methods to get current date/time in Java.
Source Code
1) Using java.util.Date
package com.beginner.examples;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample1 {
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date time = new Date();
System.out.println(df.format(time));
}
}
Output:
2019-01-25 07:36:40
2) Using java.util.Calendar
package com.beginner.examples;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DateExample2 {
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar time = Calendar.getInstance();
System.out.println(df.format(time.getTime()));
}
}
Output:
2019-01-25 07:36:40
3) Using java.time.LocalDateTime
package com.beginner.examples;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateExample3 {
public static void main(String[] args) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.now();
System.out.println(df.format(time));
}
}
Output:
2019-01-25 07:36:40
4) Using java.time.LocalDate
package com.beginner.examples;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateExample4 {
public static void main(String[] args) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate time = LocalDate.now();
System.out.println(df.format(time));
}
}
Output:
2019-01-25
Tips
As stated in the JavaDoc,LocalDate is an immutable date-time object that represents a date. But it does not store or represent a time or time-zone.
References
Imported packages in Java documentation: