JS获取两个时间内的所有月份、天数

let dates = ["2019-01-01","2021-02-28","2020-05-01","2020-05-01","2020-01-03","2020-11-02","2020-10-02","2020-01-02"]
//冒泡排序
for (let i = 0; i < dates.length; i++) {
	for (let j = 0; j < dates.length-i-1; j++) {
		if (new Date(dates[j]).getTime()>new Date(dates[j+1]).getTime()) {
			let a = dates[j]
			dates[j] = dates[j+1];
			dates[j+1] = a;
		}
	}
}
let months = [];
let days = [];
/**
 * 获取月份
 * @param {Object} minDate 最小时间 yyyy-MM-dd 
 * @param {Object} maxDate 最大时间 yyyy-MM-dd 
 */
function getDiffDate(minDate,maxDate){
	let startDate = new Date(minDate);
	let endDate = new Date(maxDate);
    //把时间的天数都设置成当前月第一天
	startDate.setDate(1)
	endDate.setDate(1)
    // new Date(yyyy-MM-dd) 不知为何有时候小时是 08 有时候是00 
    endDate.setHours(0)
	startDate.setHours(0)
	while (endDate.getTime()>=startDate.getTime()){
		let year = startDate.getFullYear();
		let month = startDate.getMonth()+1;
        //加一个月
		startDate.setMonth(month)
		if (month.toString().length == 1) {
			month = "0" + month;
		}
		months.push(year+"-"+month)
	}
}
getDiffDate(dates[0],dates[dates.length-1])
console.log(months)
console.log(dates)
/**
 * 获取天数
 * 获取区间的所有日期
 * @param {Object} start
 * @param {Object} end
 */
function getDays (minDate, maxDate) {
	let startDate = new Date(minDate);
	let endDate = new Date(maxDate);
	while (endDate.getTime() >= startDate.getTime()) {
		let year = startDate.getFullYear();
		let month = startDate.getMonth()+1
		let day = startDate.getDate()
		//加一天
		startDate.setDate(day + 1);
		if (month.toString().length == 1) {
			month = "0" + month;
		}
		if (day.toString().length == 1) {
			day = "0" + day;
		}
		days.push(year + "-" + month + "-" + day);
	}
}
getDays("2020-11-12","2021-01-01")
console.log(days)

下面方法获取指定月份有多少天, 转自(侵删):https://www.cnblogs.com/wisewrong/p/7494867.html

/**
 * 获取指定月份有多少天
 * @param {Object} date yyyy-MM-dd
 */
function getMonthLength(date) {
  // 将日期设置为下月一号
  d.setMonth(d.getMonth()+1)
  d.setDate('1')
  // 获取本月最后一天
  d.setDate(d.getDate()-1)
  return d.getDate()
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值