I have got a date in this format: Tuesday, 31st October 2017 and tried to convert it with new Date(); but it didn't work.
Is there any simple way how to convert this date into a timestamp? I am not a developer but need quickly achieve this small task.
Thank you very much.
How about this? The last line will print out the timestamp. Since your date is not in a standard format, I parsed the string and built it in the correct format for Date.parse()
to work.
var dateStr = "Tuesday, 31st October 2017";
dateStr = dateStr.replace(/.*, /, ''); //Remove leading weekday name
var arr = dateStr.split(' '); //Split into 3 parts
var dateNum = arr[0].replace(/st|nd|rd/, ''); //Strip non digits from day
var finalDateStr = arr[1] + ' ' + dateNum + ' ' + arr[2];
var dt = Date.parse(finalDateStr);
console.log(dt); //timestamp
As @serjeii mentioned in the comment you can just get rid of the strings next to the day indicating which n-th day of the month you have there.
Here is a nice 1 liner solution for you:
Date("Tuesday, 31st October 2017".replace(/(\d+)(st|nd|rd|th)/, "$1"));
Of course, you can declare your date as a variable and then call the replace function.
var my_date = "Tuesday, 31st October 2017";
Date(my_date.replace(/(\d+)(st|nd|rd|th)/, "$1"));
You are welcome :)
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.