js农历和公历转换

文章描述了一种实现农历和公历对照的JavaScript函数,使用Intl.DateTimeFormat处理日期格式,并特别关注了闰月的处理。作者通过`init`和`getChineseCalendar`函数,展示了如何获取给定日期的农历表示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

			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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值