java convert date from one timezone to another

Use Case:
Suppose you receive time string from one machine in  PST zone as "04-30-2015 07:00:00", the machine on which you receive this string data is in CST and you want to convert the time in EST.

If we use java.util.Date it will change the string into Date with reference to local machine timezone which is CST. i.e. it will look something like "04-30-2015 07:00:00 CST", so the conversion will something like below.

What will Happen
Time is EST  will be calculated as "04-30-2015 09:00:00 EST"

What is the perceived output
Time is EST  should be  "04-30-2015 10:00:00 EST"

Why It happens
java.util.Date does not take in reference of the timezone, for it time is absolute and Timezone is only interpreted as display property, and offset is applied on absolute time to print the timezone accordingly.

Solution

Use Joda time. If you are using maven include the following dependency.

 <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.7</version>
    </dependency>

and use the following method: 

 public String convertTimeZones(Date fromDate, String frmTz, String toTz) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss");
      
        /*Convert the time string into a string with valid timezone appeneded to it*/
        String fromDateTime = df.format(fromDate) + " " +DateTimeZone.forTimeZone(TimeZone.getTimeZone(frmTz));
       
        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd hh.mm.ss ZZZ");
        DateTimeFormatter fmt = DateTimeFormat.forPattern("E,MMM d yyyy hh:mm:ss zz");
        DateTime origDate = new DateTime(dtf.parseDateTime(fromDateTime));
        DateTime dtToTz = origDate.withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone(toTz)));
        return dtToTz.toString(fmt);
    }


Comments

Popular posts from this blog

Caused by: java.sql.SQLTimeoutException: ORA-01013: user requested cancel of current operation

HashiCorp Vault Integration with Ansible Etower using approle

utility to extract date from text with java