@northguild/gmt
Version:
Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.
66 lines (64 loc) • 2.72 kB
JavaScript
import { dateFromFixed, fixedFromIso, isIsoLeapYear, mod } from "./fixedDay.js";
// src/internal/temporalCompat/indianArithmetic.ts
/** Saka year = Gregorian year of its Chaitra 1 minus this. */
const SAKA_YEAR_OFFSET = 78;
const MONTHS_PER_YEAR = 12;
/** Chaitra is month 1; Vaishakha (2) to Bhadra (6) have 31 days, Ashvina (7) to Phalguna (12) 30. */
const LAST_31_DAY_MONTH = 6;
function chaitraOne(gregorianYear) {
return fixedFromIso(gregorianYear, 3, isIsoLeapYear(gregorianYear) ? 21 : 22);
}
function monthLength(sakaYear, month) {
if (month === 1) return isIsoLeapYear(sakaYear + 78) ? 31 : 30;
return month <= LAST_31_DAY_MONTH ? 31 : 30;
}
/** The Saka year, month, month code and day of a proleptic Gregorian (ISO) date. */
function indianFieldsFromIso(isoYear, isoMonth, isoDay) {
const fixed = fixedFromIso(isoYear, isoMonth, isoDay);
const gregorianYear = fixed < chaitraOne(isoYear) ? isoYear - 1 : isoYear;
const year = gregorianYear - 78;
let remaining = fixed - chaitraOne(gregorianYear);
for (let month = 1; month <= MONTHS_PER_YEAR; month++) {
const length = monthLength(year, month);
if (remaining < length) return {
year,
month,
monthCode: `M${String(month).padStart(2, "0")}`,
day: remaining + 1
};
remaining -= length;
}
throw new RangeError(`${isoYear}-${isoMonth}-${isoDay} is past its Saka year`);
}
/**
* The Indian calendar as an integer arithmetic model for `nonIsoArithmetic.ts`, so add and until
* are correct before ISO year 1 too (D5). Every answer is this file's arithmetic.
*/
const indianArithmeticModel = {
calendarId: "indian",
fields(date) {
const iso = date.withCalendar("iso8601");
return indianFieldsFromIso(iso.year, iso.month, iso.day);
},
monthOrdinal(_year, monthCode) {
const month = /^M(\d{2})$/.exec(monthCode);
const ordinal = month ? Number(month[1]) : 0;
return ordinal >= 1 && ordinal <= MONTHS_PER_YEAR ? ordinal : "missing";
},
addMonths({ year, month }, months) {
const index = year * MONTHS_PER_YEAR + month - 1 + months;
return {
year: Math.floor(index / MONTHS_PER_YEAR),
month: mod(index, MONTHS_PER_YEAR) + 1
};
},
monthsBetween: (from, to) => (to.year - from.year) * MONTHS_PER_YEAR + to.month - from.month,
daysInMonth: ({ year, month }) => monthLength(year, month),
toDate(year, month, day) {
if (month < 1 || month > MONTHS_PER_YEAR || day < 1 || day > monthLength(year, month)) throw new RangeError(`No Indian date ${year}-${month}-${day}`);
let fixed = chaitraOne(year + 78) + day - 1;
for (let earlier = 1; earlier < month; earlier++) fixed += monthLength(year, earlier);
return dateFromFixed(fixed);
}
};
export { SAKA_YEAR_OFFSET, indianArithmeticModel, indianFieldsFromIso };