我有两个输入日期从日期选择器控件。我选择了开始日期2/2/2012和结束日期2/7/2012。我为此写了以下代码。

结果应该是6,但我得到了5。

function SetDays(invoker) {   
    var start = $find('<%=StartWebDatePicker.ClientID%>').get_value();
    var end = $find('<%=EndWebDatePicker.ClientID%>').get_value();

    var oneDay=1000 * 60 * 60 * 24;
    var difference_ms = Math.abs(end.getTime() - start.getTime())
    var diffValue = Math.round(difference_ms / oneDay);
}

有人能告诉我怎样才能得到确切的差别吗?


当前回答

// today
const date = new Date();

// tomorrow
const nextDay = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);

// Difference in time
const Difference_In_Time = nextDay.getTime() - date.getTime();

// Difference in Days 
const Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

其他回答

http://momentjs.com/或https://date-fns.org/

来自Moment文档:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days')   // =1

或者包括开头:

a.diff(b, 'days')+1   // =2

避免手动打乱时间戳和时区。

根据您的具体用例,您可以选择

使用a/b.startOf('day')和/或a/b.endOf('day')强制diff在“ends”处包含或排除(正如@kotpal在评论中的建议)。 设置第三个参数为真来获得一个浮点差分,然后你可以Math。地板上,数学。ceil或数学。根据需要圆润。 选项2也可以通过获取“秒”而不是“天”,然后除以24*60*60来实现。

如果你正在使用moment.js,你可以很容易地做到这一点。

var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");

//Difference in number of days
moment.duration(start.diff(end)).asDays();

//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();

如果你想找出给定日期和当前日期之间的天数差异(忽略时间),请确保从当前日期的moment对象中删除时间,如下所示

moment().startOf('day')

找出给定日期与当前日期在天数上的差异

var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');

//Difference in number of days
moment.duration(given.diff(current)).asDays();
// today
const date = new Date();

// tomorrow
const nextDay = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);

// Difference in time
const Difference_In_Time = nextDay.getTime() - date.getTime();

// Difference in Days 
const Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

我使用Moment.js在ES6中创建了一个快速可重用的函数。

const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => { const getDateAsArray = (date) => { return moment(date.split(/\D+/), date_format); } return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1; } console.log(getDaysDiff('2019-10-01', '2019-10-30')); console.log(getDaysDiff('2019/10/01', '2019/10/30')); console.log(getDaysDiff('2019.10-01', '2019.10 30')); console.log(getDaysDiff('2019 10 01', '2019 10 30')); console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30')); console.log(getDaysDiff('2019-10-01-2019', '2019-10-30')); console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY')); console.log(getDaysDiff('10-01-2019', '10-30-2019')); console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY')); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

使用moment.js(它很容易在javascript中计算日期操作)

firstDate。diff(secondDate, 'days', false);// true|分数值为false

结果将以整数形式给出天数。