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 ofDateFormatUtils
to get an ISO8601 formatter for date-time without time zone. It is aFastDateFormat
object. - Use
ISO_DATETIME_TIME_ZONE_FORMAT
field of DateFormatUtils to get an ISO8601 formatter for date-time with time zone. It is aFastDateFormat
object. - Use
SMTP_DATETIME_FORMAT
field that is the SMTP (and probably other) date headers. It returns aFastDateFormat
object. - Use
format(Date date)
method ofFastDateFormat
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.