UNPKG

lunar-calendar-plus

Version:

lunar-calendar-plus是一个可自定义设置假期、节日;获取指定农历日期、节气、每日宜忌、天文历等灵活的js库。支持Typescript!

123 lines (108 loc) 2.86 kB
/* * @Description: * @version: * @Author: XJ * @Date: 2021-01-12 09:24:12 */ "use strict"; /** * 返回至今天数 * @param {*} y * @param {*} m * @param {*} d */ function distance(y, m, d) { return (Date.UTC(y, m, d) - Date.UTC(1900, 0, 31)) / 86400000; } function lunarDay(yearHandle) { // Year Handler this.yearHandle = yearHandle; // Year Data Cache this.yearCache = {}; // Year Data Offset this.offset = 0; } /** * 指定年月日的天数 * @param {*} dateObj */ lunarDay.prototype.calDay = function (dateObj) { this.offset = distance( dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate() ); // 当前农历所在的年份 return this.calMonth(this.calYear()); }; /** * 获取阴历月份 */ lunarDay.prototype.calMonth = function (currLeapYear) { var isLeap = false; var tempData = 0; // 存在跨年的情况,缓存里是不存在第二年的 if (!this.yearCache[currLeapYear]) this.yearCache[currLeapYear] = this.yearHandle.getLeapMonth(currLeapYear); /** * 阴历年份内所有月的天数 */ for (var currMaxMon = 1; currMaxMon < 13 && this.offset > 0; currMaxMon++) { // 如果存在闰月,则先加原本月份的天数再加上闰月的天数 if ( this.yearCache[currLeapYear].isLeap && !isLeap && currMaxMon == this.yearCache[currLeapYear].leapMonth + 1 ) { currMaxMon--; tempData = this.yearCache[currLeapYear].day; isLeap = true; } else { tempData = this.yearHandle.getMonthDay(currLeapYear, currMaxMon); } this.offset -= tempData; } /** * 当前阴历所在的月份 */ if (this.offset < 0) { --currMaxMon; this.offset += tempData; } else if ( this.offset == 0 && currMaxMon == this.yearCache[currLeapYear].leapMonth + 1 ) { // 不在并闰月且有闰月则减去一个月 --currMaxMon; } return { year: currLeapYear, month: currMaxMon, day: this.offset + 1 }; }; /** * 获取当前阴历年 * @param {*} y */ lunarDay.prototype.calYear = function () { var tempData = 0; for (var i = 1900; i < 2100 && this.offset > 0; i++) { if (this.yearCache[i]) { tempData = this.yearCache[i].allYearDay; } else { var allDay = this.yearHandle.yearDay(i); var leapYear = this.yearHandle.getLeapMonth(i); // Add Cache leapYear["allYearDay"] = leapYear["isLeap"] ? (allDay += leapYear["day"]) : allDay; this.yearCache[i] = leapYear; tempData = leapYear["allYearDay"]; } this.offset -= tempData; } // 前一年农历已经过去的天数 if (this.offset < 0) { this.offset += tempData; --i; } return i; }; module.exports = lunarDay;