js 实现干支
干支纪年法的基本概念
干支纪年法是中国传统的纪年方式,由天干(10个)和地支(12个)组合而成,共60种组合,称为一个甲子循环。天干包括:甲、乙、丙、丁、戊、己、庚、辛、壬、癸;地支包括:子、丑、寅、卯、辰、巳、午、未、申、酉、戌、亥。
干支计算的核心逻辑
干支纪年与公历年份的换算需注意:干支纪年以农历立春为分界,但通常简化处理为按公历年份计算。核心公式为:
- 天干序号 = (年份 - 4) % 10(结果小于0时加10)
- 地支序号 = (年份 - 4) % 12(结果小于0时加12)
JavaScript实现代码
function getChineseEraYear(year) {
const heavenlyStems = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
const earthlyBranches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
// 处理公元前年份(需验证历史准确性)
const baseYear = year >= 0 ? year : year + 1;
const stemIndex = (baseYear - 4) % 10;
const branchIndex = (baseYear - 4) % 12;
return {
heavenlyStem: heavenlyStems[stemIndex >= 0 ? stemIndex : stemIndex + 10],
earthlyBranch: earthlyBranches[branchIndex >= 0 ? branchIndex : branchIndex + 12],
fullName: heavenlyStems[stemIndex >= 0 ? stemIndex : stemIndex + 10] +
earthlyBranches[branchIndex >= 0 ? branchIndex : branchIndex + 12]
};
}
// 示例:获取2023年干支
console.log(getChineseEraYear(2023)); // 输出:{ heavenlyStem: '癸', earthlyBranch: '卯', fullName: '癸卯' }
边界情况处理
- 公元前年份:需注意公元无0年,公元前1年之后是公元1年。
- 年份验证:可添加参数校验确保输入为整数。
- 立春分界:精确计算需结合农历日期,上述代码采用简化处理。
扩展功能
若需计算月、日、时的干支(八字),需引入农历转换库(如lunar.js)和时辰计算。时辰地支固定对应现代时间:

- 子时:23:00-1:00
- 丑时:1:00-3:00
- ...
- 亥时:21:00-23:00
注意事项
干支纪年与公历并非严格对应,重大历史事件研究时应参考专业历法工具。此实现适用于一般场景的快速换算需求。






