Java Q & A Blog

January 30, 2010

How to change TimeZone in Java?

Filed under: 3+ year, Developer, Sr. Developer — Dev B @ 6:38 am

package com.hewitt.boomberg.util;

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.TimeZone;

public class DateUtility {

      public static String changeDateFormat(String date,  String sourceFormat,  String sourceTimeZone,  String targetFormat, String targetTimeZone)  throws ParseException {

            DateFormat oSourceFormat = new SimpleDateFormat(sourceFormat);

            DateFormat oTargetFormat = new SimpleDateFormat(targetFormat);

            TimeZone oSourceTimeZone = TimeZone.getTimeZone(sourceTimeZone);

            TimeZone oTargetTimeZone = TimeZone.getTimeZone(targetTimeZone);

            oSourceFormat.setTimeZone(oSourceTimeZone);

            oTargetFormat.setTimeZone(oTargetTimeZone);

            Date d = (Date) oSourceFormat.parse(date);

            return oTargetFormat.format(d);

      }


public class Test {

      public static void main(String[] args) throws ParseException {

            String date= “01/21/2010 08:10:14 CST”;

            String sourceFormat =”MM/dd/yyyy HH:mm:ss zzz”;

            String targetFormat = “EEE, dd MMM yyyy HH:mm:ss zzz”;

            String sourceTimeZone = “CST”;

            String targetTimeZone = “GMT”;

            String outDate=DateUtil. changeDateFormat(date, sourceFormat,   sourceTimeZone, targetFormat, targetTimeZone);

            System.out.println(outdate);

 }

} 

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.