I have two dates that I get in the following format - that are returned from a web service:
我有两个日期,我得到以下格式 - 从Web服务返回:
var dateone = "2016-08-21T07:00:00.000Z";
var datetwo = "2016-08-28T07:00:00.000Z";
var datediff = datetwo - dateone;
var numdays = Math.round(datediff);
console.log("Number of Days is " + numdays);
I get NaN
. What am I missing here?
我得到了NaN。我在这里想念的是什么?
3 个解决方案
#1
3
Your dateone
and datetwo
variables are String
s not Date
s. Try this:
dateone和datetwo变量是字符串而不是日期。尝试这个:
var dateone = new Date("2016-08-21T07:00:00.000Z");
var datetwo = new Date("2016-08-28T07:00:00.000Z");
Also, substracting 2 Date
s objects will give you the difference between them in milliseconds, if you want to determine the number of days, you can do something like this:
另外,减去2个日期对象将以毫秒为单位给出它们之间的差异,如果要确定天数,可以执行以下操作:
var dayDif = (datetwo - dateone) / 1000 / 60 / 60 / 24;
#2
1
You can easily do with moment.js
你可以轻松地使用moment.js
var a = moment('2016-08-21T07:00:00.000Z');
var b = moment('2016-08-28T07:00:00.000Z');
var days = b.diff(a, 'days');
的jsfiddle
#3
0
As well as what Titus said about turning them into Dates rather than Strings, try something like this:
除了Titus关于将它们变成日期而不是字符串的内容,请尝试这样的事情:
var oneDay = 24*60*60*1000; // Calculates milliseconds in a day
var diffDays = Math.abs((dateone.getTime() - datetwo.getTime())/(oneDay));
I don't know what you expected Math.round() to do for you, but I don't see that helping much. Math.abs() ensures that the difference is positive, while subtracting the two getTime() functions gets the difference in milliseconds.
我不知道你期望Math.round()为你做什么,但我不认为这有多大帮助。 Math.abs()确保差值为正,而减去两个getTime()函数得到的差值以毫秒为单位。
Hope this helps.
希望这可以帮助。
#1
3
Your dateone
and datetwo
variables are String
s not Date
s. Try this:
dateone和datetwo变量是字符串而不是日期。尝试这个:
var dateone = new Date("2016-08-21T07:00:00.000Z");
var datetwo = new Date("2016-08-28T07:00:00.000Z");
Also, substracting 2 Date
s objects will give you the difference between them in milliseconds, if you want to determine the number of days, you can do something like this:
另外,减去2个日期对象将以毫秒为单位给出它们之间的差异,如果要确定天数,可以执行以下操作:
var dayDif = (datetwo - dateone) / 1000 / 60 / 60 / 24;
#2
1
You can easily do with moment.js
你可以轻松地使用moment.js
var a = moment('2016-08-21T07:00:00.000Z');
var b = moment('2016-08-28T07:00:00.000Z');
var days = b.diff(a, 'days');
的jsfiddle
#3
0
As well as what Titus said about turning them into Dates rather than Strings, try something like this:
除了Titus关于将它们变成日期而不是字符串的内容,请尝试这样的事情:
var oneDay = 24*60*60*1000; // Calculates milliseconds in a day
var diffDays = Math.abs((dateone.getTime() - datetwo.getTime())/(oneDay));
I don't know what you expected Math.round() to do for you, but I don't see that helping much. Math.abs() ensures that the difference is positive, while subtracting the two getTime() functions gets the difference in milliseconds.
我不知道你期望Math.round()为你做什么,但我不认为这有多大帮助。 Math.abs()确保差值为正,而减去两个getTime()函数得到的差值以毫秒为单位。
Hope this helps.
希望这可以帮助。