Sunday, August 14, 2016

How to format dates and time using DateTimeFormatter

In these samples of code, you are going to see some ways of using DateTimeFormatter properly in Java:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CustomDatePatterns {
public static void main(String[] args) {
// patterns from simple to complex ones
String[] dateTimeFormats = {
"dd-MM-yyyy", /* d is day (in month), M is month, y is year */
"d '('E')' MMM, YYYY", /*
* E is name of the day (in week), Y is
* year
*/
"w'th week of' YYYY", /* w is the week of the year */
"EEEE, dd'th' MMMM, YYYY" /* E is day name in the week */
};
LocalDateTime now = LocalDateTime.now();
for (String dateTimeFormat : dateTimeFormats) {
System.out.printf("Pattern \"%s\" is %s %n", dateTimeFormat,
DateTimeFormatter.ofPattern(dateTimeFormat).format(now));
}
}
}

This code outputs:

Pattern "dd-MM-yyyy" is 14-08-2016 
Pattern "d '('E')' MMM, YYYY" is 14 (Sun) Aug, 2016 
Pattern "w'th week of' YYYY" is 34th week of 2016 
Pattern "EEEE, dd'th' MMMM, YYYY" is Sunday, 14th August, 2016

Example 2:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

// Using examples, illustrates how to use "pattern strings" for creating custom time formats
class CustomTimePatterns {
public static void main(String[] args) {
// patterns from simple to complex ones
String[] timeFormats = {
"h:mm", /* h is hour in am/pm (1-12), m is minute */
"hh 'o''clock'", /*
* '' is the escape sequence to print a single
* quote
*/
"H:mm a", /* H is hour in day (0-23), a is am/pm */
"hh:mm:ss:SS", /* s is seconds, S is milliseconds */
"K:mm:ss a" /* K is hour in am/pm(0-11) */
};
LocalTime now = LocalTime.now();
for (String timeFormat : timeFormats) {
System.out.printf("Time in pattern \"%s\" is %s %n", timeFormat,
DateTimeFormatter.ofPattern(timeFormat).format(now));
}
}
}

This outputs:

Time in pattern "h:mm" is 5:03 
Time in pattern "hh 'o''clock'" is 05 o'clock 
Time in pattern "H:mm a" is 17:03 PM 
Time in pattern "hh:mm:ss:SS" is 05:03:10:21 
Time in pattern "K:mm:ss a" is 5:03:10 PM 

No comments:

Post a Comment