Search code examples
javascriptdatedate-conversiondatestamp

Convert date with full month name and time to ISO date


I have a date and time stamp in the format 02 December 2016 18:00pm.

This is generated by jQuery selector:

"datestamp": $('span.article_info__published').text(),

How can I convert it to the format 2007-07-24T12:50:00+01:00?

If possible, I'd like to do it on the same line. Otherwise it needs to accommodate this sort of construction...

result = {
    "other": $('div.article__header h1').text(),
    "datestamp": $('span.article_info__published').text(),
    "more": $('meta[name="twitter:image"]').attr("content"),
    "assorted": $('figcaption.caption').text(),
};

(I can't remember the name of the destination format... I think ISO 8601?)

Update: the following returns "invalid date"...

var myDate = new Date("02 December 2016 18:00pm");

document.write(myDate);

Solution

  • For the string to be interpretable as a date for conversion, I needed to remove the time "pm" from the back of the string first.

    var date = "02 December 2016 18:00pm"
    
    date = date.slice(0, -2);
    
    var myDate = new Date(date);
    
    document.write(myDate);