UNPKG

luxon-hijri

Version:

A Hijri date converter based on the Umm al-Qura calendar system, using Luxon for date manipulations.

41 lines (40 loc) 1.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toHijri = void 0; // toHijri.ts const luxon_1 = require("luxon"); const hDates_1 = require("./hDates"); function toHijri(gregorianDate) { if (!(gregorianDate instanceof Date) || isNaN(gregorianDate.getTime())) { throw new Error('Invalid Gregorian date'); } const inputDate = luxon_1.DateTime.fromJSDate(gregorianDate).startOf('day'); const closestDate = hDates_1.hDatesTable.reduce((prev, curr) => { const currDate = luxon_1.DateTime.local(curr.gy, curr.gm, curr.gd).startOf('day'); if (currDate <= inputDate && currDate > luxon_1.DateTime.fromJSDate(prev)) { return currDate.toJSDate(); } return prev; }, new Date(0)); const correspondingHijriYear = hDates_1.hDatesTable.find((date) => { const dt = luxon_1.DateTime.local(date.gy, date.gm, date.gd).startOf('day'); return dt.toJSDate().getTime() === closestDate.getTime(); }); if (correspondingHijriYear) { const differenceInDays = inputDate.diff(luxon_1.DateTime.fromJSDate(closestDate).startOf('day'), 'days').days; let hijriYear = correspondingHijriYear.hy; let hijriMonth = 0; let remainingDays = Math.round(differenceInDays); for (let i = 0; i < 12; i++) { const daysInThisMonth = (correspondingHijriYear.dpm >> i) & 1 ? 30 : 29; if (remainingDays < daysInThisMonth) { hijriMonth = i + 1; break; } remainingDays -= daysInThisMonth; } return { hy: hijriYear, hm: hijriMonth, hd: remainingDays + 1 }; } return null; } exports.toHijri = toHijri;