Search code examples
javascriptdateutcepochdate-conversion

mismatch in local date conversion to utc epoch time and back to date in javascript


let the local date time be local : Mar 10 2014 11:52:50 GMT+0530
converting it to utc epoch time in javascript:

var epochtime=Date.UTC(2014,2,10,11,52,50);


output : 1394452370000

now converting it back to local date:

var utcSeconds =1394452370000;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);
alert(d);

output : Fri Jun 09 46158 06:03:20 GMT+0530

but required output is : Mar 10 2014 11:52:50 GMT+0530

please could someone figure out what the problem is ..?


Solution

  • Milliseconds != seconds. You're getting a value in milliseconds, but then using it as seconds.

    To turn your value back into a date, simply:

    var d = new Date(1394452370000);
    

    Example:

    var epochtime=Date.UTC(2014,2,10,11,52,50);
    var d = new Date(epochtime);
    snippet.log(d.toISOString());
    <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>