2

I have a server time (east cost of USA) that I want to convert to user's local time regardless of his location. I don't know the user's time zone.

Here is a sample date stored in MongoDB (UTC time):

ISODate("2012-05-03T09:40:34.764Z") which becomes 5/3/2012 5:40:34 AM

I want to convert this to local time of the user.

Is there a plugin I can look at or someone has it done w/o plugin?

This my code which is not working:

var svrDate = new Date('5/3/2012 5:40:34 AM');
var tzo = ((new Date()).getTimezoneOffset() / 60) * (-1);
var userTime = new Date(svrDate.setHours(svrDate.getHours() + tzo)).toLocaleString());
kheya
  • 7,546
  • 20
  • 77
  • 109
  • possible duplicate of [How to convert server time in UTC to web browser's local time?](http://stackoverflow.com/questions/10570024/how-to-convert-server-time-in-utc-to-web-browsers-local-time) -- you already asked this question and it was closed as duplicate of [this question](http://stackoverflow.com/q/6525538/218196). If you want your question to stay open, you should explicitly state why the other question does not solve your problem. You should also be specific about what exactly is not working with your code. – Felix Kling May 13 '12 at 18:25
  • Why the downvote. The problem is real, and the suggestion may be good. – Florian Mertens Feb 17 '15 at 04:56

3 Answers3

4

Simple:

var d = new Date("2012-05-03T09:40:34.764Z");
alert(d);

In my case, this prints:

Thu May 03 2012 02:40:34 GMT-0700 (PDT)

Because I'm in California.

The Z at the end of the string indicates that the date string is in UTC. JavaScript already knows how to handle that. If you want local time, just call the usual getTime(), getMonth(), getDay() methods. If you want UTC time, call their UTC variants: getUTCTime(), getUTCMonth(), getUTCDay(), etc.

Benjamin Cox
  • 6,090
  • 21
  • 19
1

Have a look at the jquery-localtime plugin at https://github.com/GregDThomas/jquery-localtime - that will convert a UTC time to the local time.

gdt
  • 1,822
  • 17
  • 19
1
`//Covert datetime by GMT offset 
//If toUTC is true then return UTC time other wise return local time
function convertLocalDateToUTCDate(date, toUTC) {
    date = new Date(date);
    //Local time converted to UTC
    console.log("Time :" + date);
    var localOffset = date.getTimezoneOffset() * 60000;
    var localTime = date.getTime();
    if (toUTC)
    {
        date = localTime + localOffset;
    }
    else
    {
        date = localTime - localOffset;
    }
    date = new Date(date);
    console.log("Converted time" + date);
    return date;
}
`