Renato Ivancic - Software Engineer

Background image

Formatting dates in java

Backend

Date Logo

Java 7

You can format the java.util.Date in Java 7 with java.text.SimpleDateFormat.

For example

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/M/yyyy");
String formatedDate = dateFormat.format(new Date());
System.out.println("Formated date: " + formatedDate); // Formated date: 01/6/2018

Java 8

In Java 8 we can replace Date class with java.time.LocalDateTime and then use java.time.format.DateTimeFormatter to format it. You can notice that the date and time responsible classes are now inside of java.time package.

Example of formatting the date like for the same value as above.

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd/M/yyy");
String formatedDate = LocalDateTime.now().format(dateFormat);
System.out.println("Formated date: " + formatDateTime); // Formated date: 01/6/2018

Patterns

Tip: Watch out! Patterns are case sensitive. In one application that I was working on, there were daily computational intensive exports running. The result files were then shared with partners. After some struggling why they can not parse the file we found out that date formatting on our side was wrong because we printed days in year instead days of month. To fix issue we had to change the pattern and rerun heavy jobs. To avoid formatting issues, if you want to print dates of the month the pattern is dd, the upper case DD stands for days in year.

Letter Date or Time Component Presentation Examples
D Day in year Number 189
d Day in month Number 10

To compare result with an example above, in case we would write DD instead of dd the result would be following

SimpleDateFormat dateFormat = new SimpleDateFormat("DD/M/yyyy");
String formatedDate = dateFormat.format(new Date()); 
System.out.println(formatedDate); // 152/6/2018

You can test date formats quickly on online date formatter. Date time online formatter

It’s even better if you crete some JUnit tests for it.

Same goes for the year format. Dont use YYYY for formatting year but yyyy. Good article about it: https://www.juandebravo.com/2015/04/10/java-yyyy-date-format

Github Java project

You can check dates formatting in action in my java examples repository.

Rivancic Github

Sources

Date time online formatter

Java 8 – How to format LocalDateTime

Juan de Bravo

Icons made by Freepik from www.flaticon.com is licensed by CC 3.0 BY

#Java #Date