Formatting Dates with Java Date/Time API


Java 8 introduced the Date&Time API, with it we had a newer and simpler way to work with dates, times in Java much better than old java.util.Date and java.util.Calendar classes. When it comes to dates and times two of the more common tasks are parsing an String to a Date-Time and formatting a Date into a String. This article is focused on those actions.

Date/Time to String

When we require to generate the String representation of a Date we need to use the format method of the Date/Time instance. This method receives a DateTimeFormatter instance where we can indicate the output format of the date.

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

LocalDateTime datetime =;
String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

It doesn’t matter if you have a LocalDateTime, LocalTime, LocalDate, or ZonedDateTime instance. The DateTimeFormatter and the format method works for all of them.

String to Date/Time

Another common task is to parse an String into a Date, that’s the purpose of the static method parse in the Date/Time classes. It requires the String we want to parse and again a DateTimeFormatter instance with pattern of that String. It will return a Date/Time instance as an output, the same time of instance as the class from where you use the parse method.

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

//Local Date Time
String datetimestring = "2021-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(datetimestring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));

//Local Date
String datestring = "2021-01-18";
LocalDateTime datetime = LocalDate.parse(datestring, DateTimeFormatter.ofPattern("yyyy-MM-dd"));


Leave a Reply

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