Optimus
Optimus

Reputation: 1624

Convert date string with AM/PM to javascript date object

I would like to convert 'April 25, 2016 Mon 09:59 PM' to a javascript date object so that I can do some basic math on it. However, Date.parse() does not work producing Nan. I assume it's because Date.parse has specific requirements for formatting.

I cannot use any external libraries besides jQuery.

Upvotes: 2

Views: 1775

Answers (2)

jcubic
jcubic

Reputation: 66570

try to remove the date of the week using regex:

var date = 'April 25, 2016 Mon 09:59 PM';
date = new Date(date.replace(/([0-9]{4}) .{3}/, '$1'));
document.body.innerHTML = date;

Upvotes: 3

Farzan
Farzan

Reputation: 617

The correct format would be:

var myDate=new Date('April 25, 2016 09:59 PM')

or

var myDate=new Date('Mon April 25, 2016 09:59 PM')

now you have a myDate object of type Date and you may access all the methods for the date object to do your calculations.

Upvotes: 0

Related Questions