Javascript DateDiff [英] Javascript DateDiff

查看:75
本文介绍了Javascript DateDiff的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到DateDiff函数问题。我想弄清楚两个日期/时间之间的差异。我已经阅读过这篇文章(什么是最好的计算方法Javascript中的日期差异)我也查看了本教程( http:// www .javascriptkit.com / javatutors / datedifference.shtml )但我似乎无法得到它。

I am having a problem with the DateDiff function. I am trying to figure out the Difference between two dates/times. I have read this posting (What's the best way to calculate date difference in Javascript) and I also looked at this tutorial (http://www.javascriptkit.com/javatutors/datedifference.shtml) but I can't seem to get it.

这是我试图与之合作的内容没有成功。有人可以告诉我我在做什么以及如何简化这一点。似乎有点过度编码......?

Here is what I tried to get to work with no success. Could someone please tell me what I am doing and how I can simplify this. Seems a little over coded...?

//Set the two dates
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var currDate = month + "/" + day + "/" + year;
var iniremDate = "8/10/2012";

//Show the dates subtracted
document.write('DateDiff is: ' + currDate - iniremDate);

//Try this function...
function DateDiff(date1, date2) {
    return date1.getTime() - date2.getTime();
}

//Print the results of DateDiff
document.write (DateDiff(iniremDate, currDate);


推荐答案

你的第一次尝试首先进行加法,然后进行减法。无论如何你都不能减去字符串,因此产生 NaN

Your first try does addition first and then subtraction. You cannot subtract strings anyway, so that yields NaN.

第二个trry没有结束。除此之外,你在字符串上调用 getTime 。您需要使用 new Date(...)。getTime()。请注意,在减去日期时,您会得到以毫秒为单位的结果。您可以通过取出整天/小时/等来格式化。

The second trry has no closing ). Apart from that, you're calling getTime on strings. You'd need to use new Date(...).getTime(). Note that you get the result in milliseconds when subtracting dates. You could format that by taking out full days/hours/etc.

这篇关于Javascript DateDiff的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆