# 如何计算两个日期之间的天数

2020/10/05 04:41 · javascript ·  · 0评论

``````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);
}
``````

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

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

1. 使用`a/b.startOf('day')`和/或`a/b.endOf('day')`强制diff在“端点”处包含或排除（如@kotpal在评论中建议）。
2. 设置第三个参数`true`来获得，然后可以浮点差异`Math.floor``Math.ceil``Math.round`根据需要。
3. 选项2也可以通过`'seconds'`代替，`'days'`然后除以来实现`24*60*60`

``````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().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();
``````

``````//Difference in days

var diff =  Math.floor(( start - end ) / 86400000);
``````

firstDate.diff（secondDate，'days'，false）; // true | false为分数值

``````const from = '2019-01-01';
const to   = '2019-01-08';

Math.abs(
moment(from, 'YYYY-MM-DD')
.startOf('day')
.diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')
) + 1
);``````

``````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>``

MVC我有两个输入文本1：天数2：日期时间选择器

`````` @Html.TextBox("HeaderINVID", null, new { @id = "HeaderINVID", @type = "number", @class = "form-control", autocomplete = "off", placeholder = "Day Count " })

@Html.TextBox("HeaderINVDT", null, new { id = "HeaderINVDT", @class = "form-control format-picker", autocomplete = "off", placeholder = " Date" })
``````

javascipt

``````    \$("#HeaderINVID").bind("keyup", function (e) {
var date = moment()
.toDate();
})
``````

``````  \$("#HeaderINVDT").bind('change', function (e) {
var NODT = moment().startOf('day');