javascript setUTCMilliseconds is wrong? Otherwise, I'm wrong
-
06-06-2021 - |
Pergunta
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)
Solução
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);
Outras dicas
To convert a UTC time in seconds to a local date object:
function makeUTC(secs) {
return new Date(Date.UTC(1970,0,1,0,0, secs, 0));
}
Note that the epoch is 1970-01-01T00:00:00.0Z
Just use the Date()
constructor with milliseconds as a number:
> new Date(1336423503 * 1000)
2012-05-07T20:45:03.000
There is no need to create a Date object and setUTCMilliseconds afterwards.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow