[随记]NodeJS获取当前日期并转成农历

在进行npm安装包时,报错:

npm ERR! code CERT_HAS_EXPIRED
npm ERR! errno CERT_HAS_EXPIRED
npm ERR! request to https://registry.npm.taobao.org/lunar-javascript failed, reason: certificate has expired

表示,证书过期,切换到官方 npm registry即可。

npm config set registry https://registry.npmjs.org/

 1、先安装2个包

npm install chinese-lunar

npm install lunar-javascript

2、直接上代码

//导入包
const chineseLunar = require('chinese-lunar');
const lunar = require('lunar-javascript');

// 定义天干和地支
const HeavenlyStems = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
const EarthlyBranches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];

// 获取天干地支年份
function getHeavenlyStemsAndEarthlyBranches(year) {
    const heavenlyStem = HeavenlyStems[(year - 4) % 10];
    const earthlyBranch = EarthlyBranches[(year - 4) % 12];
    return heavenlyStem + earthlyBranch + '年';
}

// 将数字转为中文日期
function toChineseDay(day) {
    const chineseNums = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十', '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'];
    return chineseNums[day - 1];
}

// 获取今天的公历和农历日期
function printTodayLunarCalendar() {
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth(); // 月份从0开始
    const day = today.getDate();

    const lunarDate = chineseLunar.solarToLunar(today);
    const lunarYearStemBranch = getHeavenlyStemsAndEarthlyBranches(lunarDate.year);
    const lunarMonth = lunarDate.month < 1 ? `闰${-lunarDate.month}` : lunarDate.month;
    const lunarDay = toChineseDay(lunarDate.day-1);

    console.log(`${year}年${month + 1}月${day}日 ${lunarYearStemBranch}${lunarMonth}月${lunarDay}`);
}

// 打印今天的公历和农历日期
printTodayLunarCalendar();

3、输出

2024年6月9日 甲辰年5月初四

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值