lang3

Date and Time format

With this example we are going to demonstrate how to make Date and Time formatting. We are using the org.apache.commons.lang3.time.DateFormatUtils class, that provides Date and time formatting utilities and constants. It uses the org.apache.commons.lang3.time.FastDateFormat class, that is a fast and thread-safe version of SimpleDateFormat. In short, to format Date and Time you should:

  • Create a new Date object.
  • Use ISO_DATETIME_FORMAT field of DateFormatUtils to get an ISO8601 formatter for date-time without time zone. It is a FastDateFormat object.
  • Use ISO_DATETIME_TIME_ZONE_FORMAT field of DateFormatUtils to get an ISO8601 formatter for date-time with time zone. It is a FastDateFormat object.
  • Use SMTP_DATETIME_FORMAT field that is the SMTP (and probably other) date headers. It returns a FastDateFormat object.
  • Use format(Date date) method of FastDateFormat for all formatters above to format the Date object using a GregorianCalendar.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
 
public class DateTimeFormat {
    
	public static void main(String[] args) {

  
		Date date = new Date();

   

  // Without time zone (yyyy-MM-dd'T'HH:mm:ss)

  String timestamp = DateFormatUtils.ISO_DATETIME_FORMAT.format(date);

  System.out.println("Date/time 1 = " + timestamp);
 

  // With time zone (yyyy-MM-dd'T'HH:mm:ssZZ)

  timestamp = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(date);

  System.out.println("Date/time 2 = " + timestamp);
 

   

  // US locale (EEE, dd MMM yyyy HH:mm:ss Z)

  timestamp = DateFormatUtils.SMTP_DATETIME_FORMAT.format(date);

  System.out.println("Date/time 3 = " + timestamp);
 
    }
}

Output:

Date/time 1 = 2012-07-06T18:16:31
Date/time 2 = 2012-07-06T18:16:31+03:00
Date/time 3 = Fri, 06 Jul 2012 18:16:31 +0300

  
This was an example of how to make Date and Time formatting in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button