From the Chrome console:
Me: var dateObj = new Date("2013-04-14 11:48");
undefined
Me: dateObj
Sun Apr 14 2013 11:48:00 GMT+0200 (Central Europe Daylight Time)
Me: dateObj.getUTCMilliseconds();
0
Can anyone tell me why these Date functions aren't working? I want to take a date string and turn it into UTC milliseconds. As you can see I passed the string to the Date constructor, then applied the function getUTCMilliseconds() to the returned date object. Why is it returning zero??
From the Chrome console:
Me: var dateObj = new Date("2013-04-14 11:48");
undefined
Me: dateObj
Sun Apr 14 2013 11:48:00 GMT+0200 (Central Europe Daylight Time)
Me: dateObj.getUTCMilliseconds();
0
Can anyone tell me why these Date functions aren't working? I want to take a date string and turn it into UTC milliseconds. As you can see I passed the string to the Date constructor, then applied the function getUTCMilliseconds() to the returned date object. Why is it returning zero??
Share Improve this question asked Mar 19, 2015 at 11:28 KrakenKraken 5,9403 gold badges31 silver badges52 bronze badges 2- You probably want getTime. – Mark Bolusmjak Commented Mar 19, 2015 at 11:31
- new Date().getUTCMilliseconds() also returns a nonsense answer (integer value in the hundreds instead of trillions) – Jared Smith Commented Apr 23, 2015 at 18:30
2 Answers
Reset to default 5You could use JavaScript Date valueOf() Method.
Return the primitive value of a Date object:
dateObj.valueOf()
1365929280000
The result is correct - the understanding of the function name is wrong (as was mine).
Date.getUTCMilliseconds()
is defined to return the millisecond part of the date in the same way that getMinutes()
returns the minutes stored in the object (in your example, that would return 48 minutes).
To clarify, with respect to your date [2013-04-14 11:48]
the various parts are:
getFullYear()
=== 2013getDate()
=== 14getSeconds()
=== 0 (because your date string defines a whole number of minutes)getMilliseconds()
=== 0 (for the same reason)
A counter-example may be [2017-11-15 16:53:10.78]
:
getSeconds()
=== 10getMilliseconds()
=== 78
The functions on Date
are laid out nicely on the W3Schools page here.
I looks like you were after the Unix timestamp value (which is what I wanted when Google brought me here).
Date.getTime()
will return the number of milliseconds since 1970/01/01
Luckily this is the underlying value in the current implementations, which is why the other answer works so nicely.