为什么 javascript getTime() 不是函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2627650/
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
Why javascript getTime() is not a function?
提问by udaya
I used the following function,
我使用了以下功能,
function datediff()
{
var dat1 = document.getElementById('date1').value;
alert(dat1);//i get 2010-04-01
var dat2 = document.getElementById('date2').value;
alert(dat2);// i get 2010-04-13
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((dat1.getTime() - dat2.getTime())/(oneDay));
alert(diffDays);
}
i get the error dat1.getTime()is not a function....
我得到的错误dat1.getTime()不是函数....
回答by CMS
That's because your dat1and dat2variables are just strings.
那是因为您的dat1和dat2变量只是字符串。
You should parse them to get a Dateobject, for that format I always use the following function:
您应该解析它们以获取Date对象,对于该格式,我总是使用以下函数:
// parse a date in yyyy-mm-dd format
function parseDate(input) {
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
I use this function because the Date.parse(string)(or new Date(string)) method is implementation dependent, and the yyyy-MM-ddformat will work on modern browser but noton IE, so I prefer doing it manually.
我使用这个函数是因为Date.parse(string)(or new Date(string)) 方法依赖于实现,并且yyyy-MM-dd格式可以在现代浏览器上工作,但不能在 IE 上工作,所以我更喜欢手动执行。
回答by LuckyLikey
For all those who came here and did indeed use Date typed Variables, here is the solution I found. It does also apply to TypeScript.
对于所有来到这里并确实使用日期类型变量的人,这是我找到的解决方案。它也适用于 TypeScript。
I was facing this error because I tried to compare two dates using the following Method
我正面临这个错误,因为我尝试使用以下方法比较两个日期
var res = dat1.getTime() > dat2.getTime(); // or any other comparison operator
However Im sure I used a Date object, because Im using angularjs with typescript, and I got the data from a typed API call.
但是我确定我使用了一个 Date 对象,因为我使用带有 typescript 的 angularjs,并且我从一个类型化的 API 调用中获取了数据。
Im not sure why the error is raised, but I assume that because my Object was created by JSON deserialisation, possibly the getTime()method was simply not added to the prototype.
我不确定为什么会引发错误,但我认为因为我的对象是通过 JSON 反序列化创建的,可能该getTime()方法根本没有添加到原型中。
Solution
解决方案
In this case, recreating a date-Object based on your dates will fix the issue.
在这种情况下,根据您的日期重新创建日期对象将解决该问题。
var res = new Date(dat1).getTime() > new Date(dat2).getTime()
Edit:
编辑:
I was right about this. Types will be cast to the according type but they wont be instanciated. Hence there will be a string cast to a date, which will obviously result in a runtime exception.
我是对的。类型将被转换为相应的类型,但它们不会被实例化。因此,将有一个字符串转换为日期,这显然会导致运行时异常。
The trick is, if you use interfaces with non primitive only data such as dates or functions, you will need to perform a mapping after your http request.
诀窍是,如果您使用具有非原始数据(例如日期或函数)的接口,则需要在 http 请求之后执行映射。
class Details {
description: string;
date: Date;
score: number;
approved: boolean;
constructor(data: any) {
Object.assign(this, data);
}
}
and to perform the mapping:
并执行映射:
public getDetails(id: number): Promise<Details> {
return this.http
.get<Details>(`${this.baseUrl}/api/details/${id}`)
.map(response => new Details(response.json()))
.toPromise();
}
for arrays use:
对于数组使用:
public getDetails(): Promise<Details[]> {
return this.http
.get<Details>(`${this.baseUrl}/api/details`)
.map(response => {
const array = JSON.parse(response.json()) as any[];
const details = array.map(data => new Details(data));
return details;
})
.toPromise();
}
For credits and further informationabout this topic follow the link.
有关此主题的积分和更多信息,请点击链接。
回答by Haim Evgi
To use this function/method,you need an instance of the class Date.
要使用这个函数/方法,你需要一个Date类的实例。
This method is always used in conjunction with a Dateobject.
此方法始终与Date对象结合使用。
See the code below :
请参阅下面的代码:
var d = new Date();
d.getTime();
回答by Ryan Doherty
dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function: http://www.w3schools.com/jsref/jsref_parse.asp
dat1 和 dat2 是 JavaScript 中的字符串。String 原型上没有 getTime 函数。我相信你想要 Date.parse() 函数:http: //www.w3schools.com/jsref/jsref_parse.asp
You would use it like this:
你会像这样使用它:
var date = Date.parse(dat1);

