js 实现干支
干支纪年简介
干支纪年是中国传统的纪年方式,由“天干”(甲、乙、丙、丁、戊、己、庚、辛、壬、癸)和“地支”(子、丑、寅、卯、辰、巳、午、未、申、酉、戌、亥)组合而成,共60年一个循环(称为一个甲子)。

实现逻辑
- 天干地支顺序:天干10个,地支12个,按固定顺序组合。
- 基准年份:以已知的干支年份为基准(如2024年是甲辰年),推算其他年份。
- 数学计算:通过年份与基准的差值取模,得到天干和地支的索引。
代码实现
function getChineseEraYear(year) {
// 天干和地支数组(顺序固定)
const heavenlyStems = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
const earthlyBranches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
// 基准年份:2024年是甲辰年(索引0和4)
const baseYear = 2024;
const baseStemIndex = 0; // 甲
const baseBranchIndex = 4; // 辰
// 计算差值取模
const diff = year - baseYear;
const stemIndex = (baseStemIndex + diff) % 10;
const branchIndex = (baseBranchIndex + diff) % 12;
// 处理负数情况(如year < baseYear)
const adjustedStemIndex = stemIndex >= 0 ? stemIndex : stemIndex + 10;
const adjustedBranchIndex = branchIndex >= 0 ? branchIndex : branchIndex + 12;
return heavenlyStems[adjustedStemIndex] + earthlyBranches[adjustedBranchIndex];
}
// 示例
console.log(getChineseEraYear(2024)); // 甲辰
console.log(getChineseEraYear(2000)); // 庚辰
console.log(getChineseEraYear(1990)); // 庚午
注意事项
- 基准调整:若需更早的年份,可调整基准年份(如1984年是甲子年)。
- 农历年份:实际干支年以农历春节为分界,此代码未处理农历日期,仅按公历年份近似计算。
- 负数处理:通过取模后调整索引,确保结果正确。
扩展应用
- 结合农历库(如
lunar-js)可实现精确的干支年转换。 - 添加生肖逻辑:地支对应生肖(如子鼠、丑牛)。






