日期字符串转换为 JavaScript / jQuery 中的 unix 时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11509814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date string conversion to unix timestamp in JavaScript / jQuery
提问by sozhen
I have date string in this format:
我有这种格式的日期字符串:
2009-07-15 00:00:00 - 2009-07-15 08:16:23
Could anyone help me to tweak the date string to unix timestamp into something like this:
任何人都可以帮助我将日期字符串调整为 unix 时间戳,如下所示:
1247634000 - 1247663783
I am using GMT-5
Timezone.
我正在使用GMT-5
时区。
What JavaScript or jQuery techniques could be used?
可以使用哪些 JavaScript 或 jQuery 技术?
采纳答案by Some Guy
var input = "2009-07-15 00:00:00 - 2009-07-15 08:16:23";
input = input.split(" - ").map(function (date){
return Date.parse(date+"-0500")/1000;
}).join(" - ");
Note: This won't work on old browsers since I'm using Array.map
, but I think you should easily be able to shim it.
注意:由于我使用的是旧浏览器,因此这不适用于旧浏览器Array.map
,但我认为您应该可以轻松地填充它。
回答by Grzegorz Kaczan
回答by Saket Patel
in Javascript you can directly pass the string to Date object constructor, like
在 Javascript 中,您可以直接将字符串传递给 Date 对象构造函数,例如
var date = new Date('2009-07-15 00:00:00'.split(' ').join('T'))
var date = new Date('2009-07-15 00:00:00'.split(' ').join('T'))
that will give you date object and to get timestamp from it you can do
这将为您提供日期对象并从中获取时间戳,您可以这样做
date.getTime() / 1000
date.getTime() / 1000
dividing by 1000 because getTime
will give timestamps in milliseconds
除以 1000 因为getTime
将以毫秒为单位给出时间戳
NOTE:
笔记:
Firefox is not able to parse the given date time format, so we need to convert it into proper format first, for that we just need to replace space between date and time component with 'T' that will make it a valid ISO 8601 format and firefox will be able to parse it
Firefox 无法解析给定的日期时间格式,因此我们需要先将其转换为正确的格式,为此我们只需将日期和时间组件之间的空格替换为“T”,这将使其成为有效的 ISO 8601 格式和firefox 将能够解析它
Reference:
参考:
回答by Jatin Raghav
using split method you can change the datetime formate in to date, its very simple and easy to everyone.
使用split方法可以将日期时间格式更改为日期,对每个人来说都非常简单易行。
var str = "2017-05-09T00:00:00.000Z";
var res = str.split("-",2);
var res = str.split("T",1);
var temp=res;