javascript Date().getTime() 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10395242/
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
javascript Date().getTime() is not a function
提问by Thunder Rabbit
I'm trying to compare some Dates in javascript.
我正在尝试比较 javascript 中的一些日期。
For some reason, I'm getting "Tue May 01 2012 16:43:03 GMT+0900 (JST) has no method 'getTime'"
出于某种原因,我收到“2012 年 5 月 1 日星期二 16:43:03 GMT+0900 (JST) 没有方法 'getTime'”
Of course, strings don't have methods
当然,字符串没有方法
I started with this code inside a callback, but it was failing at getTime()
on the line that creates var age
:
我从回调中的这段代码开始,但它在getTime()
创建的行上失败了var age
:
for (var i = 0; i < array_of_usage_indices.length; i++) {
store.get(array_of_usage_indices[i]['key'],function(may_need_gc) {
if(may_need_gc) {
var now = Date();
var created = Date(may_need_gc['value']);
var age = now.getTime()-created.getTime();
}
})
}
I've pared it down so my example page is literally just this:
我已经精简了它,所以我的示例页面实际上就是这样的:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>date test</title>
</head>
<body>
<script type="text/javascript" charset="utf-8">
var now = Date();
alert(now.getTime());
var t = Date().getTime();
</script>
</body>
</html>
This is failing in Chrome 18.0.1025.168 and Firefox 13.0.
这在 Chrome 18.0.1025.168 和 Firefox 13.0 中失败。
Screenshots of what I've tried:
我试过的截图:
So my question:
所以我的问题:
wth?
什么?
Do I have to use ParseDate()? Why isn't this working?
我必须使用 ParseDate() 吗?为什么这不起作用?
回答by Parv Sharma
Try using new
keyword to instantiate a new object
so instead of this
尝试使用new
关键字来实例化一个新对象而不是 this
var now = Date();
try this
尝试这个
var now = new Date();
回答by Simon
You need to use the new
operator to create a Date object.
您需要使用new
运算符来创建 Date 对象。
(new Date()).getTime()
回答by loyoliteabid
This will make 'now' as variable type as date:
这将使“现在”作为日期的变量类型:
var now = new Date();
This will get you time from 'now':
这将使您从“现在”获得时间:
new Date(now).getTime();