我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
当前回答
这里有两个问题。 首先,您只能在日期的实例上调用getTime。您需要将new Date括在括号中或将其赋值给变量。
其次,您需要以适当的格式传递一个字符串。
工作的例子:
(new Date("2012-02-26")).getTime();
其他回答
你只需要倒转你的日期数字,然后用,
new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11)
在你的情况下:
var myDate="26-02-2012";
myDate=myDate.split("-");
new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime();
附注:英国地区在这里并不重要。
您的字符串不是Date对象指定要处理的格式。您必须自己解析它,使用像MomentJS这样的日期解析库或更老的DateJS(据我所知,目前还没有维护),或者在要求date解析它之前将其调整为正确的格式(例如,2012-02-29)。
为什么你得到NaN:当你要求new Date(…)处理一个无效的字符串时,它返回一个Date对象,该对象被设置为无效的日期(new Date("29-02-2012"). tostring()返回" invalid Date ")。在此状态下对日期对象调用getTime()将返回NaN。
它应该是这个标准日期格式YYYY-MM-DD,以使用下面的等式。例如:2020-04-24 16:51:56或2020-04-24T16:51:56+05:30。它将工作良好,但日期格式应该像这样的YYYY-MM-DD。
var myDate = "2020-04-24";
var timestamp = +new Date(myDate)
/**
* Date to timestamp
* @param string template
* @param string date
* @return string
* @example datetotime("d-m-Y", "26-02-2012") return 1330207200000
*/
function datetotime(template, date){
date = date.split( template[1] );
template = template.split( template[1] );
date = date[ template.indexOf('m') ]
+ "/" + date[ template.indexOf('d') ]
+ "/" + date[ template.indexOf('Y') ];
return (new Date(date).getTime());
}
一幅图胜过千言万语:)
在这里,我将当前日期转换为时间戳,然后将时间戳转换为当前日期,我们将展示如何将日期转换为时间戳,并将时间戳转换为日期。