i need to convert from a date in string format like this "2011-05-12 16:50:44.055" to the number of milliseconds since midnight 1 January 1970 date format in Javascript
4 Answers
To ensure correct cross-browser behaviour, I think you should parse the string yourself. I moulded this answer into:
function msFromString(dateAsString)
{
var parts = dateAsString.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{3})/);
return new Date(parts[1],
parts[2] - 1,
parts[3],
parts[4],
parts[5],
parts[6],
parts[7]).getTime();
}
console.log(msFromString("2011-05-12 16:50:44.055"));
This outputs 1305211844055.
Comments
UPDATE 2023
The failure is up to the browser implementation's handling of Date.parse and how they allow for date strings not conform the date standards
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 calendar date extended format.
The format is as follows:YYYY-MM-DDTHH:mm:ss.sssZ
So we can force your string into this
const getDateFromString = str => {
const [date,time] = str.split(" ");
// reformat string into YYYY-MM-DDTHH:mm:ss.sssZ
str = `${date}T${time}Z`
return new Date(str);
};
let date = getDateFromString('2011-05-12 16:50:44.055');
console.log(date)
Comments
Have you tried the Date.parse() method? It should recognise this format (though I haven't tested that). The return value should be the number of milliseconds since 01/01/1970.
1 Comment
Date.parse only needs to accept string formatted according to RFC 1123, all other formats are browser-dependent, so you can't rely on it in this case.Make a Date object from the date string and use the getTime() method to get the milliseconds since 1 January 1970. http://www.w3schools.com/jsref/jsref_obj_date.asp
var date = new Date("2011-05-12 16:50:44.055");
document.write(date.getTime());