sandy
sandy

Reputation: 1155

Convert date in local timezone using javascript

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.

Upvotes: 1

Views: 10147

Answers (1)

Sahil Mittal
Sahil Mittal

Reputation: 20753

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!

Upvotes: 1

Related Questions