LocalDateTime class is a class that gets the current date and time and specifies the display format.
Handles dates/hours without a timezone.
By using DateTimeFormatter class, you can format the acquired date and time into the specified display format.
In the process of ①, the display format is specified by the ofPattern method of the DateTimeFormatter class.
In the process of ②, it is set by the format method of the DateTimeFormatter class.
public class Sample {
	public static void main(String[] args) {
        
        //Get the current date and time
		LocalDateTime nowDate = LocalDateTime.now();
		System.out.println(nowDate); //2020-12-20T13:32:48.293
        //Specify display format
		DateTimeFormatter dtf1 =
			DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss.SSS"); // ①
		String formatNowDate = dtf1.format(nowDate); // ②
		System.out.println(formatNowDate); // 2020/12/20 13:32:48.293
        //Specify display format
		DateTimeFormatter dtf2 =
		  DateTimeFormatter.ofPattern("yyyy year MM month dd day HH hour mm minute ss second E day");
		String formatNowDate = dtf2.format(nowDate);
		System.out.println(formatNowDate); //December 20, 2020 13:32:48 Sunday
        //Specify display format
		DateTimeFormatter dtf3 =
			DateTimeFormatter.ofPattern("yyyyMMddHHmm");
				String formatNowDate = dtf3.format(nowDate);
				System.out.println(formatNowDate); // 202012201332
 	}
}
The Date class is a date and time class based on Unix time (the elapsed time from 00:00:00 on January 1, 1970).
The SimpleDateFormat class can format the acquired date and time into a specified display format.
public class Test1 {
	public static void main(String[] args) {
		//Get the current date and time
		Date nowDate = new Date();
		System.out.println(nowDate); //Sun Dec 20 13:56:23 JST 2020
		//Specify display format
		SimpleDateFormat sdf1
		= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
		String formatNowDate = sdf1.format(nowDate);
		System.out.println(formatNowDate); // 2020/12/20 13:56:23.372
		//Specify display format
		SimpleDateFormat sdf2
		= new SimpleDateFormat("yyyy year MM month dd day HH hour mm minute ss second");
		String formatNowDate = sdf2.format(nowDate);
		System.out.println(formatNowDate); //December 20, 2020 13:56:23
 	}
}
Recommended Posts