Can I convert iso date to milliseconds? for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Use the Date() constructor to convert an ISO string to a date object, e.g. new Date('2023-07-21T09:35:31.820Z') . The Date() constructor will easily parse the ISO 8601 string and will return a Date object. Copied! We used the Date() constructor to create a Date object from an ISO string.
The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ.
To convert days to milliseconds, multiply the days by 24 for the hours, 60 for the minutes, 60 for the seconds and 1000 for the milliseconds, e.g. days * 24 * 60 * 60 * 1000 . Copied!
getTime() The getTime() method returns the number of milliseconds since the ECMAScript epoch. You can use this method to help assign a date and time to another Date object.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date var milliseconds = date.getTime(); // This will return you the number of milliseconds // elapsed from January 1, 1970 // if your date is less than that date, the value will be negative console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date
object
var myDate = new Date("2012-02-10T13:19:11+0000"); var result = myDate.getTime(); console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000"); var offset = myDate.getTimezoneOffset() * 60 * 1000; var withOffset = myDate.getTime(); var withoutOffset = withOffset - offset; console.log(withOffset); console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date
object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With