• 2024-04-27
宇哥博客 前端开发 Javascript获取两个日期间的日期,按月打印

Javascript获取两个日期间的日期,按月打印

测试代码:

  	/*
  	 * 
	* 毫秒数得到年月日
    *  eg:  (new Date(parseInt(data)*1000)).Format("yyyy-MM-dd hh:mm:ss")
    *  
    *  new Date(1522305832*1000).Format("yyyy-MM-dd hh:mm:ss")
    *  
  	*/
  	Date.prototype.format = function (fmt) {
  	    var o = {
  	        "M+": this.getMonth() + 1, //月份
  	        "d+": this.getDate(), //日
  	        "h+": this.getHours(), //小时
  	        "m+": this.getMinutes(), //分
  	        "s+": this.getSeconds(), //秒
  	        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  	        "S": this.getMilliseconds() //毫秒
  	    };
  	    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  	    for (var k in o)
  	        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  	    return fmt;
  	};
  	
/**
 * 获取两个日期间的月份数组,每个月的第一天日期
 * @param sd
 * @param ed
 * @returns {Array} eg: ['2022-11-01', '2022-12-01', '2023-01-01', '2023-02-01', '2023-03-01', '2023-04-01']
 */
function getMonthArr(sd, ed){
	var arr=[];
	if(sd>ed){
		return arr;
	}
	let ed_ym=new Date(ed.replace(/-/g, '/')).format('yyyy-MM-01');
	for(var i=0;i<100;i++){
		let sd_date=new Date(sd.replace(/-/g, '/'));
		let sd_m=sd_date.getMonth();//开始月份
		sd_date.setMonth(sd_m+i);
		let new_ym=sd_date.format('yyyy-MM-01');
		//console.log(i, '', new_ym );
		arr.push(new_ym);
		if(new_ym==ed_ym){
			break;
		}
	}
	return arr;
}

运行结果:

本文来自网络,不代表本站立场,转载请注明出处。http://www.ygbks.com/3836.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

1条评论

返回顶部