1

In my JavaScript layer, I am receiving a timestamp which is in UTC format - and I need to convert it for the local timezone. I know that the timezone can be converted using DateFormat on the Java side, but I am looking for a reliable way to do it using only JavaScript.

Any suggestions would be very appreciated.

Troy Alford
  • 26,660
  • 10
  • 64
  • 82
sandy
  • 1,153
  • 7
  • 21
  • 39
  • Take a look at these two links which will discuss more about converting date into specific culture http://jqfaq.com/how-to-parse-a-date-string-disregarding-time-zones/ and http://jqfaq.com/how-to-force-the-date-string-formats-displayed-in-your-pages-to-a-specific-culture/ – Rajagopal 웃 Dec 26 '12 at 12:59
  • I want time to be changed not format of date. – sandy Dec 26 '12 at 13:02

1 Answers1

1

Use getTimezoneOffset()

  1. Obtain local UTC offset and convert to msec

    localOffset = d.getTimezoneOffset() * 60000;
    

    Note that a negative return value from getTimezoneOffset() indicates that the current location is ahead of UTC, while a positive value indicates that the location is behind UTC.

  2. Obtain the current UTC time, by adding the local time zone offset to the local time. (localTime you will get from getTime())

    // obtain UTC time in msec
    utc = localTime + localOffset;
    
  3. Once you have obtained UTC time, obtain the destination city's UTC offset in hours, convert it to milliseconds and add it to UTC time.

    // obtain and add destination's UTC time offset
    // for example, Mumbai(India) 
    // which is UTC + 5.5 hours
    offset = 5.5;   
    mumbai = utc + (3600000*offset);
    

    At this point, the variable mumbai contains the local time in the city of Mumbai, India. This local time is expressed as the number of milliseconds since Jan 1 1970. Obviously, this isn't very readable, so we need to make a few more calculations.

  4. Change the time value calculated in the previous step to a human-readable date/time string by initializing a new Date() object with it, and calling the object's toLocaleString() method.

    // convert msec value to date string
    nd = new Date(mumbai); 
    document.writeln("Mumbai time is " + nd.toLocaleString() + "<br>");
    

And you're done!

Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
  • Obtaining offset is not reliable using above method.This might ignore day light saving.I already have client time zone and time stamp of date in UTC.Now I am to convert into calculated timezone. – sandy Dec 26 '12 at 13:53