How To Format Date And Time In Java
Chapter:
Date and Time
Last Updated:
16-09-2023 06:53:11 UTC
Program:
/* ............... START ............... */
// Using SimpleDateFormat (Java 7 and earlier):
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
// Create a SimpleDateFormat instance with the desired format pattern
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Get the current date and time
Date date = new Date();
// Format the date and time
String formattedDate = sdf.format(date);
// Print the formatted date and time
System.out.println("Formatted Date and Time: " + formattedDate);
}
}
// Using DateTimeFormatter (Java 8 and later):
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatExample {
public static void main(String[] args) {
// Create a DateTimeFormatter instance with the desired format pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// Get the current date and time
LocalDateTime dateTime = LocalDateTime.now();
// Format the date and time
String formattedDateTime = dateTime.format(formatter);
// Print the formatted date and time
System.out.println("Formatted Date and Time: " + formattedDateTime);
}
}
/* ............... END ............... */
Output
Formatted Date and Time: 2023-09-16 14:30:45
Notes:
-
In fist example, "yyyy-MM-dd HH:mm:ss" is the format pattern, where:
- yyyy represents the year with century as a decimal number.
- MM represents the month as a two-digit number.
- dd represents the day of the month as a two-digit number.
- HH represents the hour of the day (0-23) as a two-digit number.
- mm represents the minute of the hour as a two-digit number.
- ss represents the second of the minute as a two-digit number.
- In Second example, "yyyy-MM-dd HH:mm:ss" is the format pattern, and LocalDateTime is used to represent the date and time. The DateTimeFormatter class provides a flexible way to format and parse date and time objects in Java.
- Remember to replace the format patterns in the examples with the desired format you want for your date and time representation.