simone
simone

Reputation: 811

Convert date from string in javascript

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

Upvotes: 0

Views: 6186

Answers (4)

mplungjan
mplungjan

Reputation: 177684

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)

Upvotes: 1

Marcel Korpel
Marcel Korpel

Reputation: 21763

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.

Upvotes: 1

Will
Will

Reputation: 20235

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());

Upvotes: -1

EMP
EMP

Reputation: 61971

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.

Upvotes: 0

Related Questions