Wednesday, May 17, 2017

Java 8 Date and Time API: DateTimeFormatter


In this tutorial, you will learn:

  • How to format LocalDateTime (date to text)
  • How to parse (convert) String to LocalDateTime (text to date)
Example
package com.melody.datetime;

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

public class DateTimeFormatterDemo {

 public static void main(String[] args) {
  DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm:ss a");
  DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");

  // Format LocalDateTime (date to text)
  LocalDateTime currentDateTime = LocalDateTime.now();
  System.out.println("Default date & time format: " + currentDateTime);


  String formattedDateTime = currentDateTime.format(formatter1);
  System.out.println("Format LocalDateTime (date to text): " + formattedDateTime);

  // Parse (convert) String to LocalDateTime (text to date)
  String dateAsString = "05/13/2017 14:30:45";
  System.out.println("Date string to parse: " + dateAsString);

  LocalDateTime parsedDateTime = LocalDateTime.parse(dateAsString, formatter2);
  System.out.println("Parse string to LocalDateTime (text to date): " + parsedDateTime);
 }
}
Output

Default date & time format: 2017-05-17T20:41:33.205
Format LocalDateTime (date to text): 05-17-2017 08:41:33 PM
Date string to parse: 05/13/2017 14:30:45
Parse string to LocalDateTime (text to date): 2017-05-13T14:30:45



No comments:

Post a Comment