DateTimeFormatter Java Example

DateTimeFormatter Java Example

DateTimeFormatter is available in java.time.format package and include in JDK 8. This class formats and parse date time objects. Main advantage of this class is as below:

  • Use predefined constants such as ISO_DATE
  • Use pattern letters such as yyyy-MM-dd
  • Use localized styles such as medium or long.

Example to use:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd”);
LocalDate date = LocalDate.now();
String text = date.format(dateTimeFormatter);
LocalDate parsedDate = LocalDate.parse(text, dateTimeFormatter);

Detail example:

  • DateTimeFormatterExample.java:
package com.javahonk.dateformatter;

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

public class DateTimeFormatterExample {

	public static void main(String[] args) {
		
		String validPatterns1 = "EEE, MMM d, ''yy";
		String validPatterns2 = "h:mm a";
		String validPatterns3 = "YYYY-'W'ww-u";
		String validPatterns4 = "yyyy-MM-dd";
		String validPatterns5 = "yyyy-MM-dd HH:mm:ss";
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern(validPatterns1);
		System.out.println("EEE, MMM d, ''yy:--> "+LocalDateTime.now().format(formatter));
		
		formatter = DateTimeFormatter.ofPattern(validPatterns2);
		System.out.println("h:mm a:--> "+LocalDateTime.now().format(formatter));
		
		formatter = DateTimeFormatter.ofPattern(validPatterns3);
		System.out.println("YYYY-'W'ww-u:--> "+LocalDateTime.now().format(formatter));
		
		formatter = DateTimeFormatter.ofPattern(validPatterns4);
		System.out.println("yyyy-MM-dd:--> "+LocalDateTime.now().format(formatter));
		
		formatter = DateTimeFormatter.ofPattern(validPatterns5);
		System.out.println("yyyy-MM-dd HH:mm:ss:--> "+LocalDateTime.now().format(formatter));
		
		System.out.println("BASIC_ISO_DATE:--> "+LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE));
		
		System.out.println("ISO_DATE:--> "+LocalDateTime.now().format(DateTimeFormatter.ISO_DATE));
		
		System.out.println("ISO_DATE_TIME:--> "+LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));	

	}
	

}
  • Output:

DateTimeFormatter Java Example

 

  • For more information pleas visit Oracle API here

Leave a Reply

Your email address will not be published. Required fields are marked *