Thursday, December 15, 2011

Java : Simple way to get UTC/GMT date-time

In Java when you create a new Date OR Calendar object, it is initialized to the current time but in the local timezone where the program is running. For example, for a program running in India, creates a TimeZone object based on Indian Standard Time.

In your java carrier you may need to get an UTC time (Coordinated Universal Time) or GMT time (Greenwich Mean Time). For this java provides a simple class known as TimeZone, which help us to get date/time from any geographical region accross the globe. All you need to do is pass correct time zone abbreviation.

To know more about TimeZone, see API.

Below are the examples of few time zone abbreviations

AbbrNameUTC offset
AKSTAlaska Standard TimeUTC−09
ASTAtlantic Standard TimeUTC−04
CETCentral European TimeUTC+01
CTChina TimeUTC+08
ISTIndian Standard TimeUTC+05:30
SGTSingapore TimeUTC+08
UTCCoordinated Universal TimeUTC

Get list of all time zone abbreviations, click here.

/* UTCDates.java */

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

public class UTCDates {

    public static void main(String[] args) {
   
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdFormat =  new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
        String strDate;
       
        sdFormat.setTimeZone(TimeZone.getDefault());
        strDate = sdFormat.format(cal.getTime());
        System.out.println("Now : "+strDate);
       
        sdFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        strDate = sdFormat.format(cal.getTime());
        System.out.println("UTC : "+strDate);
    }

}

Output :

Now : 2011-12-15T05:25:22
UTC : 2011-12-15T11:55:22


Also Apache provides us an API to do this. To know more about it, click here.


You need to download commons-lang-x.x.jar and set it in classpath for example commons-lang-2.1.jar file.
To download commons-lang-x.x.jar, click here.

/* UTCDates.java */

import java.util.Calendar;

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

public class UTCDates {

    public static void main(String[] args) {
       
        Calendar cal = Calendar.getInstance();
        String strDate;       
       
        strDate = DateFormatUtils.ISO_DATETIME_FORMAT.format(cal.getTime());
        System.out.println("Now : "+strDate);
       
        strDate = DateFormatUtils.formatUTC(cal.getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern());
        System.out.println("UTC : "+strDate);
    }

}

More formats

FastDateFormatPattern
ISO_DATETIME_FORMATyyyy-MM-dd'T'HH:mm:ss
ISO_DATETIME_TIME_ZONE_FORMATyyyy-MM-dd'T'HH:mm:ssZZ
ISO_DATE_FORMATyyyy-MM-dd
ISO_DATE_TIME_ZONE_FORMATyyyy-MM-ddZZ
ISO_TIME_FORMAT'T'HH:mm:ss
ISO_TIME_TIME_ZONE_FORMAT'T'HH:mm:ssZZ
ISO_TIME_NO_T_FORMATHH:mm:ss
ISO_TIME_NO_T_TIME_ZONE_FORMATHH:mm:ssZZ
SMTP_DATETIME_FORMATEEE, dd MMM yyyy HH:mm:ss Z

No comments:

Post a Comment