How do I format date and time using DateFormatUtils class?

The DateFormatUtils class help us to format date and time information. This class use an instance of org.apache.commons.lang.time.FastDateFormat class to format the date and time information. Compared to Java SimpleDateFormat, the FastDateFormat class is thread safe.

If you want to create a custom date format you can use the FastDateFormat class directly.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.time.DateFormatUtils;

import java.util.Date;

public class DateFormattingDemo {
    public static void main(String[] args) {
        Date today = new Date();

        // ISO8601 formatter for date-time without time zone.
        // The format used is yyyy-MM-dd'T'HH:mm:ss.
        String timestamp = DateFormatUtils.ISO_DATETIME_FORMAT.format(today);
        System.out.println("timestamp = " + timestamp);

        // ISO8601 formatter for date-time with time zone.
        // The format used is yyyy-MM-dd'T'HH:mm:ssZZ.
        timestamp = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(today);
        System.out.println("timestamp = " + timestamp);

        // The format used is EEE, dd MMM yyyy HH:mm: ss Z in US locale.
        timestamp = DateFormatUtils.SMTP_DATETIME_FORMAT.format(today);
        System.out.println("timestamp = " + timestamp);
    }
}

The result of the code snippet:

timestamp = 2017-05-12T22:45:59
timestamp = 2017-05-12T22:45:59+08:00
timestamp = Fri, 12 May 2017 22:45:59 +0800

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.