Converting date from one timezone to another in groovy

09 / Feb / 2011 by Vishal Sahu 6 comments

Hi,
In my recent grails project, i came across the situation where i needed to convert the date in given timezone to the date in another timezone. I searched a lot about it and got many solutions for this problem and then i came out with a simple way to do so.

Lets i have a date in TimeZone say oldTimeZone and i want to convert it to another timeZone say newTimeZone, so to convert it to another timezone, i wrote the method given below.

 

public Date convertToNewTimeZone(Date date, TimeZone oldTimeZone, TimeZone newTimeZone){

      long oldDateinMilliSeconds=date.time - oldtimeZone.rawOffset
      // oldtimeZone.rawOffset returns the difference(in milliSeconds) of time in that timezone with the time in GMT
      // date.time returns the milliseconds of the date

      Date dateInGMT=new Date(oldDateinMilliSeconds)

      long convertedDateInMilliSeconds = dateInGMT.time + newTimeZone.rawOffset
      Date convertedDate = new Date(convertedDateInMilliSeconds)

    return convertedDate
}

 

This Works for me.
Hope it helps.

Cheers..!!!
Vishal Sahu
vishal@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (6)

  1. Mona

    I am in similar situation. I am trying to convert my dateTime groovy object (EST) from DB to PST.
    But my results are not right using your solution.

    Thank You!

    Reply
  2. Vishal sahu

    Hi Har,

    Yes this code wont work for DST.

    If you want to cover DST also, then replace the “rawOffset” with “getOffset((new Date()).time)”

    So the modified code would be:-
    Date date=new Date()
    long oldDateinMilliSeconds=date.time – oldtimeZone.getOffset(date.time)

    Date dateInGMT=new Date(oldDateinMilliSeconds)

    long convertedDateInMilliSeconds = dateInGMT.time + newTimeZone.getOffset(date.time)

    Date convertedDate = new Date(convertedDateInMilliSeconds)

    Thanks.

    Reply
  3. Vishal sahu

    Hi Lari,
    thanks for sharing the code.
    Code provided by me is helpful when you know the date and its timezone as well.
    In my scenario i wanted to convert the date that is stored in some other timezone on my machine, i know the date and its timezone and thus converted it by using this code and it works fine for me.

    Reply
  4. Lari H

    I think this code is in-correct for most users. The internals of java.util.Date is always UTC. You should just format the date in another TimeZone instead. The same thing applies for parsing dates (set the TimeZone on the DateFormat used for parsing).

    Example code:

    import java.text.*
    dateformat=DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL)
    dateformat.setTimeZone(TimeZone.getTimeZone(‘America/Los_Angeles’))
    dateformat.format(new Date())

    Reply

Leave a comment -