How to convert and format DATE from different TIME ZONEs

Below Java code snippet is an example of how to convert date from different time zone.



//////////////////////////////Java Code Snippet/////////////////////////////////////


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


public class Test {

    public static void main(String[] args) {
       
        String pattern = "MM-dd-yyyy hh:mm aa";
        String dateStr = "2014-08-07T03:24:17Z";
       
        getFormatedDisplayDate(dateStr, pattern,"GMT", "CST");
    }
   

    /**
     * Dates formats for conversion.
     */
    private static final SimpleDateFormat[] DATE_FORMATS = {
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"), //ISO8601 long RFC822 zone
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"), //ISO8601 long long form zone
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"), //ignore timezone
        new SimpleDateFormat("yyyyMMddHHmmssZ"), //ISO8601 short
        new SimpleDateFormat("yyyyMMddHHmm"),
        new SimpleDateFormat("yyyyMMdd"),
        new SimpleDateFormat("yyyyMM"),
        new SimpleDateFormat("yyyy")
    };

   

    /**
     * Returns a converted date based on date pattern and time zone.
     * @param dateStr
     * @param datePattern
     * @param timeZoneStr
     * @return foramttedDate
     */
    public static String getFormatedDisplayDate(String dateStr, String datePattern, String fromTimeZoneStr, String toTimeZoneStr){
       
        System.out.println( "dateStr =" + dateStr + ", datePattern =" + datePattern
                + ", fromTimeZoneStr ="+ fromTimeZoneStr +", toTimeZoneStr ="+ toTimeZoneStr);
       
        String foramttedDate = null;
       
        //From Time Zone.
        TimeZone fromTimeZone = getTimeZone(fromTimeZoneStr);
   
        //To Time Zone
        TimeZone toTimeZone = getTimeZone(toTimeZoneStr);
   
       
        //Conversion.
        Date convertedDate  = null;
        for (SimpleDateFormat sdf : DATE_FORMATS) {
            try {
                sdf.setLenient(false);
                sdf.setTimeZone(fromTimeZone);
                convertedDate  = sdf.parse(dateStr);
                System.out.println( "#Date : " + dateStr + " matched with pattern : " + sdf.toPattern());
               
                break;
            } catch (Exception e) {
                //do nothing: //continue;
            }
        }
       
        //Formatting.
        if(convertedDate!= null){
           
            Calendar cal = new GregorianCalendar(toTimeZone);
            cal.setTime(convertedDate);
           
            System.out.println( "##to date timezone =" + cal.getTimeZone());
            System.out.println( "##to date =" + cal.getTime());
           
            SimpleDateFormat sdf = null;
            try {
                sdf = new SimpleDateFormat(datePattern);
            } catch (Exception e) {
                System.out.println("ERROR occured while reading date pattern. Invalid date pattern passed. " + e.getMessage());
                e.printStackTrace();
            }
           
            if(sdf != null){
                foramttedDate =  sdf.format(cal.getTime());
            }
           
        }else{
            System.out.println( "Invalid date or no such date formate found. Data cound not be formated.");
        }
       
        System.out.println( "foramttedDate =" + foramttedDate);
        return foramttedDate;
    }
   
   
   
    /**
     * Returns TimeZone setting given timeZoneStr.
     * If the timeZoneStr is null, it will set default current System time zone.
     * @param timeZoneStr
     * @return Null if errors or TimeZone.
     */
    public static final TimeZone getTimeZone(String timeZoneStr){
        TimeZone timeZone = null;
       
        if(timeZoneStr == null || timeZoneStr.equals("")){
            System.out.println( "Creating defualt System Time zone.");
            timeZone = TimeZone.getDefault(); //Default;
        }else{
            try {
                timeZone = TimeZone.getTimeZone(timeZoneStr);
            } catch (Exception e) {
                System.out.println("ERROR occured while creating TimeZone for given timeZoneStr = " + timeZoneStr);
                e.printStackTrace();
            }
        }

        return timeZone;
    }
   
}



/////////////////////Output////////////////////////////////////////////////////////

dateStr =2014-08-07T03:24:17Z, datePattern =MM-dd-yyyy hh:mm aa, fromTimeZoneStr =GMT, toTimeZoneStr =CST

#Date : 2014-08-07T03:24:17Z matched with pattern : yyyy-MM-dd'T'HH:mm:ss

##to date timezone =sun.util.calendar.ZoneInfo[id="CST",offset=-21600000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=CST,offset=-21600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]

##to date =Wed Aug 06 22:24:17 CDT 2014

foramttedDate =08-06-2014 10:24 PM










Comments