简体   繁体   中英

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.

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; 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM