In your Java application you want to format date-time objects using the new date and time API introduced in JDK 8. A solution to this problem is to use the java.time.format.DateTimeFormatter
. The DateTimeFormatter
class provides formatter for printing and parsing date-time objects.
With this class we can format the date-time objects using a predefined constants, there are many predefined ready to use formats, such as ISO_DATE
, ISO_DATE_TIME
. You can also use letters pattern to format the date-time objects, for instance using the dd MMMM yyyy
. The formatter can format in localized style, in a long
or medium
style.
Let’s see an example below:
package org.kodejava.datetime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class DateTimeFormatterDemo {
public static void main(String[] args) {
// Get system current date and time.
LocalDateTime time = LocalDateTime.now();
// Get an instance of DateTimeFormatter and print a
// formatted version of the system current date-time
// using a predefined formatter.
DateTimeFormatter format = DateTimeFormatter.ISO_DATE_TIME;
System.out.printf("Time: %s%n", time.format(format));
// Create a custom formatter and format the date-time
// object.
DateTimeFormatter customFormat =
DateTimeFormatter.ofPattern("MMMM d, yyyy hh:mm a");
System.out.printf("Time: %s%n", time.format(customFormat));
// Create a custom formatter with locale and format the
// date-time object.
DateTimeFormatter localeFormat =
DateTimeFormatter.ofPattern("d MMM yyyy HH:mm:ss",
Locale.FRENCH);
System.out.printf("Time: %s%n", time.format(localeFormat));
}
}
The results of the code above are:
Time: 2021-11-16T07:51:16.1247212
Time: November 16, 2021 07:51 AM
Time: 16 nov. 2021 07:51:16
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024