Search code examples
javascriptdateutcmilliseconds

javascript setUTCMilliseconds is wrong? Otherwise, I'm wrong


Am I implementing setUTCMilliseconds incorrectly? I get the incorrect date for any value I put in. Here is just one example of a wrong value. All my test data resolves to May 24 (the future from now) in JS, but in C# or using quick online conversion tools, my UTS MS are correct.

any thoughts?

function parseDate(epoch) {   
    var d = new Date();

    //tried this too, but it shows me the actual epoch 1970 date instead
    //var d = new Date(0);

    //EDIT: this should be seconds in combination with Date(0)
    d.setUTCMilliseconds(parseInt(epoch)); 

    return d.toString();
}

 // 1336423503 -> Should be Mon May 07 2012 13:45:03 GMT-7

 // javascript says
 Thu May 24 2012 05:03:21 GMT-0700 (Pacific Daylight Time) 

Solution

  • From a similar question:

    var utcMilliseconds = 1234567890000;
    var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
    d.setUTCMilliseconds(utcMilliseconds);
    

    See Convert UTC Epoch to local date with javascript.