开发日志:生成json格式的日期数据

在项目中,因为使用的插件 mPicker.js 的限制,写了一段生成日期 json 的代码,在此记录一下。

生成格式如下,年 child 里有12个月的 child 下有对应的日:
json格式

代码可以生成前49年、后50年和当前年,一共100年的日期:

function getDateJson() {
    
    
	var _prevY = [],
    	_nextY = [],
    	_allY = [],
    	_allM = [],
    	_allD = [];
	var def = new Date(),
    	year = def.getFullYear(),
        month = def.getMonth() + 1,
        day = def.getDate();
	for (var i = 1; i <= 31; i++) {
    
     // 日
		_allD.push({
    
     "name": (i < 10 ? ('0' + i) : i) + '日', "value": (i < 10 ? ('0' + i) : i) })
	}
	for (var i = 1; i <= 12; i++) {
    
     // 月
		var _monthD = Object.assign([], _allD);
		switch(i) {
    
    
    		case 4, 6, 9, 11:
	    		_monthD.splice(_monthD.length, 1);
    			break;
    		default:
    			break;
		}
		_allM.push({
    
     "name": (i < 10 ? ('0' + i) : i) + '月', "value": (i < 10 ? ('0' + i) : i), child: _monthD });
	}
	for (var i = 49; i >= 0; i--) {
    
    
		var _upY = year + i + 1;
		var _downY = year - i;
		var _yearD = Object.assign([], _allM);

		// 后50年
		if((_downY%4==0 && _downY%100!=0) || (_downY%100==0 && _downY%400==0)) {
    
    
			_yearD[1].child.splice(28, 1)
			_prevY.push({
    
     "name": _downY + '年', "value": _downY + '', child: _yearD });
		} else {
    
    
			_yearD[1].child.splice(29, 1)
			_prevY.push({
    
     "name": _downY + '年', "value": _downY + '', child: _yearD });
		}

		// 前50年
		if((_upY%4==0 && _upY%100!=0) || (_upY%100==0 && _upY%400==0)) {
    
    
			_yearD[1].child.splice(28, 1)
			_nextY.unshift({
    
     "name": _upY + '年', "value": _upY + '', child: _yearD });
		} else {
    
    
			_yearD[1].child.splice(29, 1)
			_nextY.unshift({
    
     "name": _upY + '年', "value": _upY + '', child: _yearD });
		}
	}
	_allY = _prevY.concat(_nextY);
	return _allY;
}

附:

2月天数的计算
  二月份的天数主要取决于年份是不是闰年,如果是闰年则29天,不是闰年则28天。
  一般的在数学运算中,或者在公历纪年法中,能被4整除的大多是闰年,除了那些能被100整除而不能被400整除的年份以外。
  1、非世纪年能被4整除,且不能被100整除的是闰年。(如2004年是闰年,1901年不是闰年)
  2、世纪年能被400整除的是闰年。(如2000年少闰年,1900年不是闰年)

猜你喜欢

转载自blog.csdn.net/qq_37992222/article/details/112324707