我有一个时间字符串,格式如下 YYYY-MM-DD hh:mm:ss
。
我想将其转换为相当于使用 Javascript 将日期字符串传递给 mysql unix_timestamp 函数。
我尝试解析日期并将其传递给 Date.UTC()
函数,但它似乎给出了与我想要的不同的时间。帮助。
最佳答案
如果您提供的是 UTC 时间戳并且想要自 1/1/1970 以来的秒数,则:
[...]
编辑
重温了我原来的回答,不喜欢,下面的比较好:
// Given an ISO8601 UTC timestamp, or one formatted per the OP,
// return the time in seconds since 1970-01-01T00:00:00Z
function toSecondsSinceEpoch(s) {
s = s.split(/[-A-Z :\.]/i);
var d = new Date(Date.UTC(s[0], --s[1], s[2], s[3], s[4], s[5]));
return Math.round(d.getTime()/1000);
}
请注意,OP 中的字符串不符合 ISO8601 标准,但上面的字符串可以使用它。如果时间戳在本地时区,则:
// Given an ISO8601 timestamp in the local timezone, or one formatted per the OP,
// return the time in seconds since 1970-01-01T00:00:00Z
function toSecondsSinceEpochLocal(s) {
s = s.split(/[-A-Z :\.]/i);
var d = new Date(s[0],--s[1],s[2],s[3],s[4],s[5]);
return Math.round(d.getTime()/1000);
}
如果要容纳小数秒,则需要多做一些工作才能将小数部分转换为毫秒。
关于javascript - 如何使用 javascript 从日期转换为 unix_timestamp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9780712/