Date in Java is formatted using java.time.format.DateTimeFormatter class that formats a date in a particular format. Current date or time is fetched using java.time.LocalDateTime using now() method that returns the current date.
Date returns using now() method is in the format - yyyy-MM-ddTHH:mm:ss. For example, 2017-11-09T19:14:10.402
There are different ways to define the formatter as shown below:
1) DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("yyyy-MM-dd HH:mm:ss").toFormatter(Locale.ENGLISH);
2) DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
Below is the sample program to format a date and get a date in String format.
package com.learning; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.util.Locale; public class DateFormatJava8 { public static void main(String args[]) { LocalDateTime now = LocalDateTime.now(); System.out.println("Original Date - " + now); DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("yyyy-MM-dd HH:mm:ss").toFormatter(Locale.ENGLISH); String formattedDate = now.format(formatter); System.out.println("Formatted Date - " + formattedDate); } }
Output:
Original Date - 2017-11-09T19:19:49.428 Formatted Date - 2017-11-09 19:19:49
No comments:
Post a Comment