原生js农历和公历的转化

159 阅读1分钟

实现了一个一年内农历和公历的简易对照功能,一些细节上没做出来,还有闰二月这个也没过多处理

			const dateTimeFormat = new Intl.DateTimeFormat('zh-u-ca-chinese')
			const dateTimeFormat2 = new Intl.DateTimeFormat('zh-ch',{month:'2-digit',day:'2-digit',year:'numeric'})
			const regex = /(\d{4})年(\D+)(\d{1,2})/;
			const monthContrast = {
				'正月': '01',
				'二月': '02',
				'闰二月': '02',
				'三月': '03',
				'四月': '04',
				'五月': '05',
				'六月': '06',
				'七月': '07',
				'八月': '08',
				'九月': '09',
				'十月': '10',
				'十一月': '11',
				'腊月': '12'

			}
			function init() {
				const currYear = new Date().getFullYear()
				let tagday = `${currYear}/01/01`,
					indexDay = tagday;
				let chineseCa = getChineseCalendar(new Date(tagday))
				console.log(chineseCa, 'tagday', tagday)


				do {
					// 先查找到正月初一
					let a = new Date(indexDay)
					indexDay = a.setDate(a.getDate() + 1)
					chineseCa = getChineseCalendar(new Date(indexDay))
					console.log(dateTimeFormat2.format(indexDay), chineseCa)
				} while (tagday != chineseCa);

				// 再次循环,直到农历为第二年的正月初一
				let nextYear = new Date(chineseCa)
				nextYear =dateTimeFormat2.format( nextYear.setFullYear(nextYear.getFullYear()+1))

				
				let ontrast = {}
				do {
					let a = new Date(indexDay)
					indexDay = a.setDate(a.getDate() + 1)
					chineseCa = getChineseCalendar(new Date(indexDay))
					ontrast[dateTimeFormat2.format(indexDay)] = chineseCa
				} while (nextYear != chineseCa);
				console.log(ontrast)
			}

			function getChineseCalendar(date) {
				let dateString = dateTimeFormat.format(date)
				let [all, year, month, day] = dateString.match(regex);
				return `${year}/${monthContrast[month]}/${day.padStart(2, '0')}`
			}
			init()