In this article, we will see how to change the datetime format in Java.
Datetime format patterns
Format patterns are predefined letters such as “yyyy” for the year, “MM” for the month, and “dd” for the day. Formatting and parsing the DateTime objects in Java is done using the format patterns.
Knowing in detail about these format patterns is very much needed. I have provided the reference link below to refer to the Oracle official page about these formats.
Changing the Datetime object format
Using the SimpleDateFormat class, we can change the format of a DateTime object in Java. See the following example, for more information on this.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeFormatter {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(now);
System.out.println("Formatted Date: " + formattedDate);
}
}
We have created a SimpleDateFormat object and specified the required format pattern as a parameter. Upon calling the format()
method, the current date and time will be formatted to the pattern which we provided.
Convert string into Datetime object
If you have datetime in a string format, then you need to convert this into a Datetime object in order to change its format. You can use the parse()
method of the SimpleDateFormat class to convert the string into a Datetime object.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeParser {
public static void main(String[] args) {
String dateString = "2023-06-30 15:30:00";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date parsedDate = formatter.parse(dateString);
System.out.println("Parsed Date: " + parsedDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
In the above example, the dateString contains the datetime in a string format and we create a SimpleDateFormat object with the corresponding format pattern and call the parse()
method, which returns a DateTime object representing the parsed date and time.
References:
Oracle Documentation: SimpleDateFormat Class (https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/text/SimpleDateFormat.html)