所选日期对应月份的天数

  • 本文关键字:日期 javascript date momentjs
  • 更新时间 :
  • 英文 :


我需要从两个日期之间选择的月份中找到天数。例如,如果我选择date1为2021年1月1日,date2为2021年3月1日,那么我需要得到1月、2月和3月的总天数。

输出=

1月天数+2月天数+3月天数= 31+28+31

What I tried:

const getDiff=(selectedDate1,selectedDate2)=>{
console.log('Date check',moment(selectedDate1).daysInMonth(),moment(new Date()).daysInMonth())
if(moment(selectedDate1).daysInMonth() - moment(selectedDate2).daysInMonth() ===0){
return Number(moment(selectedDate1).daysInMonth())
}else{
return Number(moment(selectedDate1).daysInMonth())+Number(moment(selectedDate2).daysInMonth())
}
}

但是使用此代码,我只获得所选日期的天数总和,即。only一月份的天数+三月份的天数

使用moment.js,你只会得到开始月份的开始和结束月份的结束之间的天数加1(因为月底不包括最后一天,加1比去下一个月的开始更简单),例如

function wholeMonthDays(d1, d2) {
let diff = moment(d2).endOf('month').diff(moment(d1).startOf('month'),'days') + 1; 
return diff;
}
let start = new Date(2021,0,21);
let end = new Date(2021,2,11);
console.log(wholeMonthDays(start, end)); // 90
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

或者您可以在end之后转到月初以获取差值:

function wholeMonthDays(d1, d2) {
let start = moment(d1).startOf('month');
let end = moment(d2).startOf('month').add(1, 'month');
let diff = end.diff(start, 'days');
return diff;
}
let start = new Date(2021, 0, 21);
let end = new Date(2021, 2, 11);
console.log(wholeMonthDays(start, end)); // 90
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

我将日期设置为在一个月内,以显示它添加了"月中的天数"。而不仅仅是两个日期之间的差异。

如果你真的想要一个每月总天数的数组,只需将开始设置为月末,获取日期,添加一个月,设置为月末,等等,直到超过月末。

以下几点:

  1. 请记住,Java和JavaScript中的月份是(愚蠢地)基于0的。第一个月是二月

  2. 要获得一个月的天数,您可以使用Date对象并转到下个月的第一天,然后减去1天,然后调用getDay。

  3. 两个日期之间的时间(以毫秒为单位)为

    var d1 = ...;
    var d2 = ...;
    var duration = Math.abs(d2.getTime() - d1.getTime());
    

您可以将duration除以毫秒(1000),秒(60),分钟(60)等,以获得您要

的单位时间跨度。

最简单的方法是:

// 'lo' and 'hi' could be of type Date or numbers coming from Date.getTime()
const daysBetween = (lo, hi) => {
const oneDayInMilliseconds
= 1000 // one sec has 1000 millis
* 3600 // one hour has 3600 seconds
* 24;  // one day has 24 hours
return (hi - lo) / oneDayInMilliseconds;
}

最新更新