简体   繁体   English

将日期转换为时间戳 javascript

[英]Convert date to timestamp javascript

I have got a date in this format: Tuesday, 31st October 2017 and tried to convert it with new Date();我有一个这种格式的日期: 2017 年 10 月 31 日星期二,并尝试使用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.由于您的日期不是标准格式,我解析了字符串并以正确的格式构建它,以便Date.parse()工作。

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.正如@serjeii 在评论中提到的,您可以去掉指示您所在月份的第 n 天的日期旁边的字符串。

Here is a nice 1 liner solution for you:这是一个很好的 1 衬里解决方案:

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 :)不客气 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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