@thyrith/momentkh 2.5.4 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1052 @@
1
+ "use strict";
2
+ /**
3
+ * MomentKH - Standalone Khmer Calendar Library (TypeScript)
4
+ *
5
+ * A simplified, standalone library for Khmer calendar conversion
6
+ * No dependencies required
7
+ *
8
+ * Based on:
9
+ * - khmer_calendar.cpp implementation
10
+ * - Original momentkh library
11
+ *
12
+ * @version 2.0.0
13
+ * @license MIT
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.momentkh = exports.DayOfWeek = exports.EraYear = exports.AnimalYear = exports.MonthIndex = exports.MoonPhase = void 0;
17
+ // ============================================================================
18
+ // Type Definitions
19
+ // ============================================================================
20
+ // Enums for better type safety and ease of use
21
+ var MoonPhase;
22
+ (function (MoonPhase) {
23
+ MoonPhase[MoonPhase["Waxing"] = 0] = "Waxing";
24
+ MoonPhase[MoonPhase["Waning"] = 1] = "Waning"; // រោច
25
+ })(MoonPhase || (exports.MoonPhase = MoonPhase = {}));
26
+ var MonthIndex;
27
+ (function (MonthIndex) {
28
+ MonthIndex[MonthIndex["Mikasar"] = 0] = "Mikasar";
29
+ MonthIndex[MonthIndex["Bos"] = 1] = "Bos";
30
+ MonthIndex[MonthIndex["Meak"] = 2] = "Meak";
31
+ MonthIndex[MonthIndex["Phalgun"] = 3] = "Phalgun";
32
+ MonthIndex[MonthIndex["Chetr"] = 4] = "Chetr";
33
+ MonthIndex[MonthIndex["Visakh"] = 5] = "Visakh";
34
+ MonthIndex[MonthIndex["Jesth"] = 6] = "Jesth";
35
+ MonthIndex[MonthIndex["Asath"] = 7] = "Asath";
36
+ MonthIndex[MonthIndex["Srap"] = 8] = "Srap";
37
+ MonthIndex[MonthIndex["Photrobot"] = 9] = "Photrobot";
38
+ MonthIndex[MonthIndex["Assoch"] = 10] = "Assoch";
39
+ MonthIndex[MonthIndex["Kadek"] = 11] = "Kadek";
40
+ MonthIndex[MonthIndex["BothmakAsath"] = 12] = "BothmakAsath";
41
+ MonthIndex[MonthIndex["TutiyakAsath"] = 13] = "TutiyakAsath"; // ទុតិយាសាឍ
42
+ })(MonthIndex || (exports.MonthIndex = MonthIndex = {}));
43
+ var AnimalYear;
44
+ (function (AnimalYear) {
45
+ AnimalYear[AnimalYear["Chhut"] = 0] = "Chhut";
46
+ AnimalYear[AnimalYear["Chlov"] = 1] = "Chlov";
47
+ AnimalYear[AnimalYear["Khal"] = 2] = "Khal";
48
+ AnimalYear[AnimalYear["Thos"] = 3] = "Thos";
49
+ AnimalYear[AnimalYear["Rong"] = 4] = "Rong";
50
+ AnimalYear[AnimalYear["Masagn"] = 5] = "Masagn";
51
+ AnimalYear[AnimalYear["Momee"] = 6] = "Momee";
52
+ AnimalYear[AnimalYear["Momae"] = 7] = "Momae";
53
+ AnimalYear[AnimalYear["Vok"] = 8] = "Vok";
54
+ AnimalYear[AnimalYear["Roka"] = 9] = "Roka";
55
+ AnimalYear[AnimalYear["Cho"] = 10] = "Cho";
56
+ AnimalYear[AnimalYear["Kor"] = 11] = "Kor"; // កុរ - Pig
57
+ })(AnimalYear || (exports.AnimalYear = AnimalYear = {}));
58
+ var EraYear;
59
+ (function (EraYear) {
60
+ EraYear[EraYear["Samridhisak"] = 0] = "Samridhisak";
61
+ EraYear[EraYear["Ekasak"] = 1] = "Ekasak";
62
+ EraYear[EraYear["Tosak"] = 2] = "Tosak";
63
+ EraYear[EraYear["Tresak"] = 3] = "Tresak";
64
+ EraYear[EraYear["Chatvasak"] = 4] = "Chatvasak";
65
+ EraYear[EraYear["Panchasak"] = 5] = "Panchasak";
66
+ EraYear[EraYear["Chhasak"] = 6] = "Chhasak";
67
+ EraYear[EraYear["Saptasak"] = 7] = "Saptasak";
68
+ EraYear[EraYear["Atthasak"] = 8] = "Atthasak";
69
+ EraYear[EraYear["Novvasak"] = 9] = "Novvasak"; // នព្វស័ក
70
+ })(EraYear || (exports.EraYear = EraYear = {}));
71
+ var DayOfWeek;
72
+ (function (DayOfWeek) {
73
+ DayOfWeek[DayOfWeek["Sunday"] = 0] = "Sunday";
74
+ DayOfWeek[DayOfWeek["Monday"] = 1] = "Monday";
75
+ DayOfWeek[DayOfWeek["Tuesday"] = 2] = "Tuesday";
76
+ DayOfWeek[DayOfWeek["Wednesday"] = 3] = "Wednesday";
77
+ DayOfWeek[DayOfWeek["Thursday"] = 4] = "Thursday";
78
+ DayOfWeek[DayOfWeek["Friday"] = 5] = "Friday";
79
+ DayOfWeek[DayOfWeek["Saturday"] = 6] = "Saturday"; // សៅរ៍
80
+ })(DayOfWeek || (exports.DayOfWeek = DayOfWeek = {}));
81
+ // ============================================================================
82
+ // Constants and Locale Data
83
+ // ============================================================================
84
+ const LunarMonths = {
85
+ 'មិគសិរ': 0, 'បុស្ស': 1, 'មាឃ': 2, 'ផល្គុន': 3,
86
+ 'ចេត្រ': 4, 'ពិសាខ': 5, 'ជេស្ឋ': 6, 'អាសាឍ': 7,
87
+ 'ស្រាពណ៍': 8, 'ភទ្របទ': 9, 'អស្សុជ': 10, 'កត្ដិក': 11,
88
+ 'បឋមាសាឍ': 12, 'ទុតិយាសាឍ': 13
89
+ };
90
+ const LunarMonthNames = [
91
+ 'មិគសិរ', 'បុស្ស', 'មាឃ', 'ផល្គុន', 'ចេត្រ', 'ពិសាខ',
92
+ 'ជេស្ឋ', 'អាសាឍ', 'ស្រាពណ៍', 'ភទ្របទ', 'អស្សុជ', 'កត្ដិក',
93
+ 'បឋមាសាឍ', 'ទុតិយាសាឍ'
94
+ ];
95
+ const SolarMonthNames = [
96
+ 'មករា', 'កុម្ភៈ', 'មីនា', 'មេសា', 'ឧសភា', 'មិថុនា',
97
+ 'កក្កដា', 'សីហា', 'កញ្ញា', 'តុលា', 'វិច្ឆិកា', 'ធ្នូ'
98
+ ];
99
+ const AnimalYearNames = [
100
+ 'ជូត', 'ឆ្លូវ', 'ខាល', 'ថោះ', 'រោង', 'ម្សាញ់',
101
+ 'មមី', 'មមែ', 'វក', 'រកា', 'ច', 'កុរ'
102
+ ];
103
+ const EraYearNames = [
104
+ 'សំរឹទ្ធិស័ក', 'ឯកស័ក', 'ទោស័ក', 'ត្រីស័ក', 'ចត្វាស័ក',
105
+ 'បញ្ចស័ក', 'ឆស័ក', 'សប្តស័ក', 'អដ្ឋស័ក', 'នព្វស័ក'
106
+ ];
107
+ const WeekdayNames = [
108
+ 'អាទិត្យ', 'ចន្ទ', 'អង្គារ', 'ពុធ', 'ព្រហស្បតិ៍', 'សុក្រ', 'សៅរ៍'
109
+ ];
110
+ const WeekdayNamesShort = ['អា', 'ច', 'អ', 'ព', 'ព្រ', 'សុ', 'ស'];
111
+ const MoonStatusNames = ['កើត', 'រោច'];
112
+ const MoonStatusShort = ['ក', 'រ'];
113
+ const MoonDaySymbols = [
114
+ '᧡', '᧢', '᧣', '᧤', '᧥', '᧦', '᧧', '᧨', '᧩', '᧪',
115
+ '᧫', '᧬', '᧭', '᧮', '᧯', '᧱', '᧲', '᧳', '᧴', '᧵',
116
+ '᧶', '᧷', '᧸', '᧹', '᧺', '᧻', '᧼', '᧽', '᧾', '᧿'
117
+ ];
118
+ const KhmerNumerals = {
119
+ '0': '០', '1': '១', '2': '២', '3': '៣', '4': '៤',
120
+ '5': '៥', '6': '៦', '7': '៧', '8': '៨', '9': '៩'
121
+ };
122
+ // Exceptional New Year moments (cached values for specific years)
123
+ const khNewYearMoments = {
124
+ '1879': '12-04-1879 11:36',
125
+ '1897': '13-04-1897 02:00',
126
+ '2011': '14-04-2011 13:12',
127
+ '2012': '14-04-2012 19:11',
128
+ '2013': '14-04-2013 02:12',
129
+ '2014': '14-04-2014 08:07',
130
+ '2015': '14-04-2015 14:02',
131
+ '2024': '13-04-2024 22:17',
132
+ };
133
+ // ============================================================================
134
+ // Utility Functions
135
+ // ============================================================================
136
+ function toKhmerNumeral(num) {
137
+ return String(num).replace(/\d/g, d => KhmerNumerals[d]);
138
+ }
139
+ function isGregorianLeapYear(year) {
140
+ return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
141
+ }
142
+ function getDaysInGregorianMonth(year, month) {
143
+ const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
144
+ if (month === 2 && isGregorianLeapYear(year)) {
145
+ return 29;
146
+ }
147
+ return daysInMonth[month - 1];
148
+ }
149
+ // Julian Day Number conversion
150
+ function gregorianToJulianDay(year, month, day) {
151
+ const a = Math.floor((14 - month) / 12);
152
+ const y = year + 4800 - a;
153
+ const m = month + 12 * a - 3;
154
+ return day + Math.floor((153 * m + 2) / 5) + 365 * y +
155
+ Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 32045;
156
+ }
157
+ function julianDayToGregorian(jdn) {
158
+ const a = jdn + 32044;
159
+ const b = Math.floor((4 * a + 3) / 146097);
160
+ const c = a - Math.floor((146097 * b) / 4);
161
+ const d = Math.floor((4 * c + 3) / 1461);
162
+ const e = c - Math.floor((1461 * d) / 4);
163
+ const m = Math.floor((5 * e + 2) / 153);
164
+ const day = e - Math.floor((153 * m + 2) / 5) + 1;
165
+ const month = m + 3 - 12 * Math.floor(m / 10);
166
+ const year = 100 * b + d - 4800 + Math.floor(m / 10);
167
+ return { year, month, day };
168
+ }
169
+ function getDayOfWeek(year, month, day) {
170
+ const jdn = gregorianToJulianDay(year, month, day);
171
+ // JDN % 7: where 0=Monday, 1=Tuesday, ..., 6=Sunday
172
+ // We want: 0=Sunday, 1=Monday, ..., 6=Saturday
173
+ // So we need to convert: (jdn + 1) % 7
174
+ return (jdn + 1) % 7;
175
+ }
176
+ // ============================================================================
177
+ // Input Validation Functions
178
+ // ============================================================================
179
+ /**
180
+ * Validates Gregorian date parameters
181
+ * @throws {Error} If any parameter is invalid
182
+ */
183
+ function validateGregorianDate(year, month, day, hour = 0, minute = 0, second = 0) {
184
+ // Validate types
185
+ if (typeof year !== 'number' || isNaN(year)) {
186
+ throw new Error(`Invalid year: ${year}. Year must be a valid number.`);
187
+ }
188
+ if (typeof month !== 'number' || isNaN(month)) {
189
+ throw new Error(`Invalid month: ${month}. Month must be a valid number.`);
190
+ }
191
+ if (typeof day !== 'number' || isNaN(day)) {
192
+ throw new Error(`Invalid day: ${day}. Day must be a valid number.`);
193
+ }
194
+ if (typeof hour !== 'number' || isNaN(hour)) {
195
+ throw new Error(`Invalid hour: ${hour}. Hour must be a valid number.`);
196
+ }
197
+ if (typeof minute !== 'number' || isNaN(minute)) {
198
+ throw new Error(`Invalid minute: ${minute}. Minute must be a valid number.`);
199
+ }
200
+ if (typeof second !== 'number' || isNaN(second)) {
201
+ throw new Error(`Invalid second: ${second}. Second must be a valid number.`);
202
+ }
203
+ // Validate month range (1-12)
204
+ if (month < 1 || month > 12) {
205
+ throw new Error(`Invalid month: ${month}. Month must be between 1 and 12.`);
206
+ }
207
+ // Validate day range for the specific month/year
208
+ const daysInMonth = getDaysInGregorianMonth(year, month);
209
+ if (day < 1 || day > daysInMonth) {
210
+ const monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
211
+ 'July', 'August', 'September', 'October', 'November', 'December'];
212
+ throw new Error(`Invalid day: ${day}. ${monthNames[month - 1]} ${year} has ${daysInMonth} days.`);
213
+ }
214
+ // Validate hour (0-23)
215
+ if (hour < 0 || hour > 23) {
216
+ throw new Error(`Invalid hour: ${hour}. Hour must be between 0 and 23.`);
217
+ }
218
+ // Validate minute (0-59)
219
+ if (minute < 0 || minute > 59) {
220
+ throw new Error(`Invalid minute: ${minute}. Minute must be between 0 and 59.`);
221
+ }
222
+ // Validate second (0-59)
223
+ if (second < 0 || second > 59) {
224
+ throw new Error(`Invalid second: ${second}. Second must be between 0 and 59.`);
225
+ }
226
+ }
227
+ /**
228
+ * Validates Khmer date parameters
229
+ * @throws {Error} If any parameter is invalid
230
+ */
231
+ function validateKhmerDate(day, moonPhase, monthIndex, beYear) {
232
+ // Validate types
233
+ if (typeof day !== 'number' || isNaN(day)) {
234
+ throw new Error(`Invalid day: ${day}. Day must be a valid number.`);
235
+ }
236
+ if (typeof moonPhase !== 'number' || isNaN(moonPhase)) {
237
+ throw new Error(`Invalid moonPhase: ${moonPhase}. moonPhase must be a valid number.`);
238
+ }
239
+ if (typeof monthIndex !== 'number' || isNaN(monthIndex)) {
240
+ throw new Error(`Invalid monthIndex: ${monthIndex}. monthIndex must be a valid number.`);
241
+ }
242
+ if (typeof beYear !== 'number' || isNaN(beYear)) {
243
+ throw new Error(`Invalid beYear: ${beYear}. beYear must be a valid number.`);
244
+ }
245
+ // Validate day (1-15)
246
+ if (day < 1 || day > 15) {
247
+ throw new Error(`Invalid day: ${day}. Lunar day must be between 1 and 15.`);
248
+ }
249
+ // Validate moonPhase (0 = Waxing, 1 = Waning)
250
+ const moonPhaseNum = typeof moonPhase === 'number' ? moonPhase : moonPhase;
251
+ if (moonPhaseNum !== 0 && moonPhaseNum !== 1) {
252
+ throw new Error(`Invalid moonPhase: ${moonPhase}. moonPhase must be 0 (Waxing/កើត) or 1 (Waning/រោច).`);
253
+ }
254
+ // Validate monthIndex (0-13)
255
+ const monthIndexNum = typeof monthIndex === 'number' ? monthIndex : monthIndex;
256
+ if (monthIndexNum < 0 || monthIndexNum > 13) {
257
+ throw new Error(`Invalid monthIndex: ${monthIndex}. monthIndex must be between 0 and 13.`);
258
+ }
259
+ // Validate beYear (reasonable range: 2000-3000)
260
+ if (beYear < 2000 || beYear > 3000) {
261
+ throw new Error(`Invalid beYear: ${beYear}. beYear must be between 2000 and 3000.`);
262
+ }
263
+ // Additional validation: check if leap months (12, 13) are used in non-leap years
264
+ // This is done in the conversion function since it requires more complex logic
265
+ }
266
+ /**
267
+ * Validates JavaScript Date object
268
+ * @throws {Error} If Date object is invalid
269
+ */
270
+ function validateDateObject(date) {
271
+ if (!(date instanceof Date)) {
272
+ throw new Error('Invalid input: Expected a Date object.');
273
+ }
274
+ if (isNaN(date.getTime())) {
275
+ throw new Error('Invalid Date object: Date is not a valid date.');
276
+ }
277
+ }
278
+ // ============================================================================
279
+ // Era Conversions
280
+ // ============================================================================
281
+ function adToJs(adYear) {
282
+ return adYear - 638;
283
+ }
284
+ function adToBe(adYear) {
285
+ return adYear + 544;
286
+ }
287
+ function beToAd(beYear) {
288
+ return beYear - 544;
289
+ }
290
+ function jsToAd(jsYear) {
291
+ return jsYear + 638;
292
+ }
293
+ function beToJs(beYear) {
294
+ return beYear - 1182;
295
+ }
296
+ function jsToBe(jsYear) {
297
+ return jsYear + 1182;
298
+ }
299
+ // ============================================================================
300
+ // Calendar Calculation Functions
301
+ // ============================================================================
302
+ function getAharkun(beYear) {
303
+ return Math.floor((beYear * 292207 + 499) / 800) + 4;
304
+ }
305
+ function getAharkunMod(beYear) {
306
+ return (beYear * 292207 + 499) % 800;
307
+ }
308
+ function getKromthupul(beYear) {
309
+ return 800 - getAharkunMod(beYear);
310
+ }
311
+ function getAvoman(beYear) {
312
+ return (getAharkun(beYear) * 11 + 25) % 692;
313
+ }
314
+ function getBodithey(beYear) {
315
+ const aharkun = getAharkun(beYear);
316
+ return (Math.floor((aharkun * 11 + 25) / 692) + aharkun + 29) % 30;
317
+ }
318
+ function isKhmerSolarLeap(beYear) {
319
+ return getKromthupul(beYear) <= 207;
320
+ }
321
+ function isKhmerLeapDayByCalculation(beYear) {
322
+ const avoman = getAvoman(beYear);
323
+ const isSolarLeap = isKhmerSolarLeap(beYear);
324
+ if (avoman === 0 && getAvoman(beYear - 1) === 137) {
325
+ return true;
326
+ }
327
+ else if (isSolarLeap) {
328
+ return avoman < 127;
329
+ }
330
+ else if (avoman === 137 && getAvoman(beYear + 1) === 0) {
331
+ return false;
332
+ }
333
+ else if (avoman < 138) {
334
+ return true;
335
+ }
336
+ return false;
337
+ }
338
+ function isKhmerLeapMonth(beYear) {
339
+ const bodithey = getBodithey(beYear);
340
+ const boditheyNextYear = getBodithey(beYear + 1);
341
+ if (bodithey === 25 && boditheyNextYear === 5) {
342
+ return false;
343
+ }
344
+ return (bodithey === 24 && boditheyNextYear === 6) ||
345
+ (bodithey >= 25) ||
346
+ (bodithey < 6);
347
+ }
348
+ function getLeapType(beYear) {
349
+ if (isKhmerLeapMonth(beYear)) {
350
+ return 1; // Leap month (អធិកមាស)
351
+ }
352
+ else if (isKhmerLeapDayByCalculation(beYear)) {
353
+ return 2; // Leap day (ចន្ទ្រាធិមាស)
354
+ }
355
+ else if (isKhmerLeapMonth(beYear - 1)) {
356
+ let previousYear = beYear - 1;
357
+ while (true) {
358
+ if (isKhmerLeapDayByCalculation(previousYear)) {
359
+ return 2;
360
+ }
361
+ previousYear -= 1;
362
+ if (!isKhmerLeapMonth(previousYear)) {
363
+ return 0;
364
+ }
365
+ }
366
+ }
367
+ return 0; // Regular year
368
+ }
369
+ function getNumberOfDaysInKhmerMonth(monthIndex, beYear) {
370
+ const leapType = getLeapType(beYear);
371
+ const idx = typeof monthIndex === 'number' ? monthIndex : monthIndex;
372
+ if (idx === MonthIndex.Jesth && leapType === 2) { // ជេស្ឋ with leap day
373
+ return 30;
374
+ }
375
+ if (idx === MonthIndex.BothmakAsath || idx === MonthIndex.TutiyakAsath) { // បឋមាសាឍ, ទុតិយាសាឍ
376
+ return leapType === 1 ? 30 : 0;
377
+ }
378
+ // Alternating pattern: even months = 29 days, odd months = 30 days
379
+ // មិគសិរ:29, បុស្ស:30, មាឃ:29, ផល្គុន:30, ចេត្រ:29, ពិសាខ:30, ជេស្ឋ:29, អាសាឍ:30, etc.
380
+ return idx % 2 === 0 ? 29 : 30;
381
+ }
382
+ function getNumberOfDaysInKhmerYear(beYear) {
383
+ const leapType = getLeapType(beYear);
384
+ if (leapType === 1)
385
+ return 384; // Leap month
386
+ if (leapType === 2)
387
+ return 355; // Leap day
388
+ return 354; // Regular
389
+ }
390
+ function nextMonthOf(monthIndex, beYear) {
391
+ const leapType = getLeapType(beYear);
392
+ const idx = typeof monthIndex === 'number' ? monthIndex : monthIndex;
393
+ if (idx === MonthIndex.Jesth && leapType === 1) { // ជេស្ឋ in leap month year
394
+ return MonthIndex.BothmakAsath; // បឋមាសាឍ
395
+ }
396
+ if (idx === MonthIndex.Kadek)
397
+ return MonthIndex.Mikasar; // កត្ដិក -> មិគសិរ
398
+ if (idx === MonthIndex.BothmakAsath)
399
+ return MonthIndex.TutiyakAsath; // បឋមាសាឍ -> ទុតិយាសាឍ
400
+ if (idx === MonthIndex.TutiyakAsath)
401
+ return MonthIndex.Srap; // ទុតិយាសាឍ -> ស្រាពណ៍
402
+ return (idx + 1);
403
+ }
404
+ function previousMonthOf(monthIndex, beYear) {
405
+ const leapType = getLeapType(beYear);
406
+ const idx = typeof monthIndex === 'number' ? monthIndex : monthIndex;
407
+ if (idx === MonthIndex.Mikasar)
408
+ return MonthIndex.Kadek; // មិគសិរ -> កត្ដិក
409
+ if (idx === MonthIndex.Srap && leapType === 1)
410
+ return MonthIndex.TutiyakAsath; // ស្រាពណ៍ -> ទុតិយាសាឍ (leap)
411
+ if (idx === MonthIndex.TutiyakAsath)
412
+ return MonthIndex.BothmakAsath; // ទុតិយាសាឍ -> បឋមាសាឍ
413
+ if (idx === MonthIndex.BothmakAsath)
414
+ return MonthIndex.Jesth; // បឋមាសាឍ -> ជេស្ឋ
415
+ return (idx - 1);
416
+ }
417
+ // ============================================================================
418
+ // Khmer New Year Calculation (JS Year based)
419
+ // ============================================================================
420
+ function getAharkunJs(jsYear) {
421
+ const h = jsYear * 292207 + 373;
422
+ return Math.floor(h / 800) + 1;
423
+ }
424
+ function getAvomanJs(jsYear) {
425
+ return (getAharkunJs(jsYear) * 11 + 650) % 692;
426
+ }
427
+ function getKromthupulJs(jsYear) {
428
+ return 800 - ((292207 * jsYear + 373) % 800);
429
+ }
430
+ function getBoditheyJs(jsYear) {
431
+ const aharkun = getAharkunJs(jsYear);
432
+ const a = 11 * aharkun + 650;
433
+ return (aharkun + Math.floor(a / 692)) % 30;
434
+ }
435
+ function isAdhikameas(jsYear) {
436
+ const bodithey = getBoditheyJs(jsYear);
437
+ const boditheyNext = getBoditheyJs(jsYear + 1);
438
+ if (bodithey === 24 && boditheyNext === 6)
439
+ return true;
440
+ if (bodithey === 25 && boditheyNext === 5)
441
+ return false;
442
+ return bodithey > 24 || bodithey < 6;
443
+ }
444
+ function isChantrathimeas(jsYear) {
445
+ const avoman = getAvomanJs(jsYear);
446
+ const avomanNext = getAvomanJs(jsYear + 1);
447
+ const avomanPrev = getAvomanJs(jsYear - 1);
448
+ const isSolarLeap = getKromthupulJs(jsYear) <= 207;
449
+ if (avoman === 0 && avomanPrev === 137)
450
+ return true;
451
+ if (isSolarLeap)
452
+ return avoman < 127;
453
+ if (avoman === 137 && avomanNext === 0)
454
+ return false;
455
+ if (!isSolarLeap && avoman < 138)
456
+ return true;
457
+ if (avomanPrev === 137 && avoman === 0)
458
+ return true;
459
+ return false;
460
+ }
461
+ function has366Days(jsYear) {
462
+ return getKromthupulJs(jsYear) <= 207;
463
+ }
464
+ function getSunInfo(jsYear, sotin) {
465
+ const infoOfPrevYear = {
466
+ kromathopol: getKromthupulJs(jsYear - 1)
467
+ };
468
+ // Sun average as Libda
469
+ const r2 = 800 * sotin + infoOfPrevYear.kromathopol;
470
+ const reasey = Math.floor(r2 / 24350);
471
+ const r3 = r2 % 24350;
472
+ const angsar = Math.floor(r3 / 811);
473
+ const r4 = r3 % 811;
474
+ const l1 = Math.floor(r4 / 14);
475
+ const libda = l1 - 3;
476
+ const sunAverageAsLibda = (30 * 60 * reasey) + (60 * angsar) + libda;
477
+ // Left over
478
+ const s1 = ((30 * 60 * 2) + (60 * 20));
479
+ let leftOver = sunAverageAsLibda - s1;
480
+ if (sunAverageAsLibda < s1) {
481
+ leftOver += (30 * 60 * 12);
482
+ }
483
+ const kaen = Math.floor(leftOver / (30 * 60));
484
+ // Last left over
485
+ let rs = -1;
486
+ if ([0, 1, 2].includes(kaen)) {
487
+ rs = kaen;
488
+ }
489
+ else if ([3, 4, 5].includes(kaen)) {
490
+ rs = (30 * 60 * 6) - leftOver;
491
+ }
492
+ else if ([6, 7, 8].includes(kaen)) {
493
+ rs = leftOver - (30 * 60 * 6);
494
+ }
495
+ else if ([9, 10, 11].includes(kaen)) {
496
+ rs = ((30 * 60 * 11) + (60 * 29) + 60) - leftOver;
497
+ }
498
+ const lastLeftOver = {
499
+ reasey: Math.floor(rs / (30 * 60)),
500
+ angsar: Math.floor((rs % (30 * 60)) / 60),
501
+ libda: rs % 60
502
+ };
503
+ // Khan and pouichalip
504
+ let khan, pouichalip;
505
+ if (lastLeftOver.angsar >= 15) {
506
+ khan = 2 * lastLeftOver.reasey + 1;
507
+ pouichalip = 60 * (lastLeftOver.angsar - 15) + lastLeftOver.libda;
508
+ }
509
+ else {
510
+ khan = 2 * lastLeftOver.reasey;
511
+ pouichalip = 60 * lastLeftOver.angsar + lastLeftOver.libda;
512
+ }
513
+ // Chhaya sun
514
+ const chhayaSunMap = [
515
+ { multiplicity: 35, chhaya: 0 },
516
+ { multiplicity: 32, chhaya: 35 },
517
+ { multiplicity: 27, chhaya: 67 },
518
+ { multiplicity: 22, chhaya: 94 },
519
+ { multiplicity: 13, chhaya: 116 },
520
+ { multiplicity: 5, chhaya: 129 }
521
+ ];
522
+ const chhayaSun = khan <= 5 ? chhayaSunMap[khan] : { multiplicity: 0, chhaya: 134 };
523
+ const q = Math.floor((pouichalip * chhayaSun.multiplicity) / 900);
524
+ const pholAsLibda = q + chhayaSun.chhaya;
525
+ // Sun inauguration
526
+ const sunInaugurationAsLibda = kaen <= 5
527
+ ? sunAverageAsLibda - pholAsLibda
528
+ : sunAverageAsLibda + pholAsLibda;
529
+ return {
530
+ sunInaugurationAsLibda,
531
+ reasey: Math.floor(sunInaugurationAsLibda / (30 * 60)),
532
+ angsar: Math.floor((sunInaugurationAsLibda % (30 * 60)) / 60),
533
+ libda: sunInaugurationAsLibda % 60
534
+ };
535
+ }
536
+ function getNewYearInfo(jsYear) {
537
+ const sotins = has366Days(jsYear - 1)
538
+ ? [363, 364, 365, 366]
539
+ : [362, 363, 364, 365];
540
+ const newYearsDaySotins = sotins.map(sotin => getSunInfo(jsYear, sotin));
541
+ // Find time of new year
542
+ let timeOfNewYear = { hour: 0, minute: 0 };
543
+ for (const sotin of newYearsDaySotins) {
544
+ if (sotin.angsar === 0) {
545
+ const minutes = (24 * 60) - (sotin.libda * 24);
546
+ timeOfNewYear = {
547
+ hour: Math.floor(minutes / 60) % 24,
548
+ minute: minutes % 60
549
+ };
550
+ break;
551
+ }
552
+ }
553
+ // Number of Vanabat days
554
+ const numberOfVanabatDays = (newYearsDaySotins[0].angsar === 0) ? 2 : 1;
555
+ return {
556
+ timeOfNewYear,
557
+ numberOfVanabatDays,
558
+ newYearsDaySotins
559
+ };
560
+ }
561
+ // ============================================================================
562
+ // Khmer Date Class
563
+ // ============================================================================
564
+ class KhmerDate {
565
+ constructor(day, moonPhase, monthIndex, beYear) {
566
+ this.day = day;
567
+ this.moonPhase = moonPhase;
568
+ this.monthIndex = monthIndex;
569
+ this.beYear = beYear;
570
+ }
571
+ // Get day number (0-29) - converts from 1-based internal to 0-based external
572
+ getDayNumber() {
573
+ if (this.moonPhase === MoonPhase.Waxing) { // កើត
574
+ return this.day - 1; // day 1-15 → dayNum 0-14
575
+ }
576
+ else { // រោច
577
+ return 15 + (this.day - 1); // day 1-15 → dayNum 15-29
578
+ }
579
+ }
580
+ static fromDayNumber(dayNum) {
581
+ // Converts from 0-based dayNum to 1-based day
582
+ if (dayNum < 15) {
583
+ return { day: dayNum + 1, moonPhase: MoonPhase.Waxing }; // dayNum 0-14 → day 1-15
584
+ }
585
+ else {
586
+ return { day: (dayNum - 15) + 1, moonPhase: MoonPhase.Waning }; // dayNum 15-29 → day 1-15
587
+ }
588
+ }
589
+ addDays(count) {
590
+ if (count === 0)
591
+ return this;
592
+ if (count < 0)
593
+ return this.subtractDays(-count);
594
+ let result = new KhmerDate(this.day, this.moonPhase, this.monthIndex, this.beYear);
595
+ let remaining = count;
596
+ while (remaining > 0) {
597
+ const daysInMonth = getNumberOfDaysInKhmerMonth(result.monthIndex, result.beYear);
598
+ const currentDayNum = result.getDayNumber();
599
+ const daysLeftInMonth = (daysInMonth - 1) - currentDayNum;
600
+ if (remaining <= daysLeftInMonth) {
601
+ const newDayNum = currentDayNum + remaining;
602
+ const newDay = KhmerDate.fromDayNumber(newDayNum);
603
+ let newBeYear = result.beYear;
604
+ if (result.monthIndex === MonthIndex.Visakh) { // ពិសាខ
605
+ if (result.moonPhase === MoonPhase.Waxing && newDay.moonPhase === MoonPhase.Waning) {
606
+ newBeYear++;
607
+ }
608
+ }
609
+ result = new KhmerDate(newDay.day, newDay.moonPhase, result.monthIndex, newBeYear);
610
+ remaining = 0;
611
+ }
612
+ else {
613
+ remaining -= (daysLeftInMonth + 1);
614
+ const nextMonth = nextMonthOf(result.monthIndex, result.beYear);
615
+ const newBeYear = (result.monthIndex === MonthIndex.Chetr) ? result.beYear + 1 : result.beYear;
616
+ result = new KhmerDate(1, MoonPhase.Waxing, nextMonth, newBeYear); // Start at 1កើត
617
+ }
618
+ }
619
+ return result;
620
+ }
621
+ subtractDays(count) {
622
+ if (count === 0)
623
+ return this;
624
+ let result = new KhmerDate(this.day, this.moonPhase, this.monthIndex, this.beYear);
625
+ let remaining = count;
626
+ while (remaining > 0) {
627
+ const currentDayNum = result.getDayNumber();
628
+ if (remaining <= currentDayNum) {
629
+ const newDayNum = currentDayNum - remaining;
630
+ const newDay = KhmerDate.fromDayNumber(newDayNum);
631
+ let newBeYear = result.beYear;
632
+ if (result.monthIndex === MonthIndex.Visakh) { // ពិសាខ
633
+ if (result.moonPhase === MoonPhase.Waning && newDay.moonPhase === MoonPhase.Waxing) {
634
+ newBeYear--;
635
+ }
636
+ }
637
+ result = new KhmerDate(newDay.day, newDay.moonPhase, result.monthIndex, newBeYear);
638
+ remaining = 0;
639
+ }
640
+ else {
641
+ remaining -= (currentDayNum + 1);
642
+ const prevMonth = previousMonthOf(result.monthIndex, result.beYear);
643
+ const newBeYear = (result.monthIndex === MonthIndex.Visakh) ? result.beYear - 1 : result.beYear;
644
+ const daysInPrevMonth = getNumberOfDaysInKhmerMonth(prevMonth, newBeYear);
645
+ const newDay = KhmerDate.fromDayNumber(daysInPrevMonth - 1);
646
+ result = new KhmerDate(newDay.day, newDay.moonPhase, prevMonth, newBeYear);
647
+ }
648
+ }
649
+ return result;
650
+ }
651
+ toString() {
652
+ return `${this.day}${MoonStatusNames[this.moonPhase]} ខែ${LunarMonthNames[this.monthIndex]} ព.ស.${this.beYear}`;
653
+ }
654
+ }
655
+ // ============================================================================
656
+ // Main Conversion Functions
657
+ // ============================================================================
658
+ // Helper function to get approximate BE year (like original getMaybeBEYear)
659
+ function getMaybeBEYear(year, month) {
660
+ // SolarMonth['មេសា'] = 3 (0-based), so month <= 4 (1-based)
661
+ if (month <= 4) {
662
+ return year + 543;
663
+ }
664
+ else {
665
+ return year + 544;
666
+ }
667
+ }
668
+ // Cache for Visakha Bochea dates by year
669
+ const visakhaBocheaCache = {};
670
+ // Cache for New Year Full Info
671
+ const newYearInfoCache = {};
672
+ /**
673
+ * Find BE Year transition datetime for a given Gregorian year
674
+ * BE year increases on ១រោច ខែពិសាខ (1st waning day of Pisakh = dayNumber 15 of month 5)
675
+ * Returns timestamp in milliseconds at midnight of that day
676
+ */
677
+ function getVisakhaBochea(year, isSearching = false) {
678
+ if (visakhaBocheaCache[year]) {
679
+ return visakhaBocheaCache[year];
680
+ }
681
+ // Search for 1រោច Pisakh (when BE year changes) - start from April since it typically occurs then
682
+ for (let searchMonth = 4; searchMonth <= 6; searchMonth++) {
683
+ const daysInMonth = new Date(year, searchMonth, 0).getDate();
684
+ for (let searchDay = 1; searchDay <= daysInMonth; searchDay++) {
685
+ // Avoid infinite recursion by using simplified BE year during search
686
+ const result = gregorianToKhmerInternal(year, searchMonth, searchDay, 12, 0, 0, true);
687
+ if (result.khmer.monthIndex === MonthIndex.Visakh && result._khmerDateObj.getDayNumber() === 15) {
688
+ // Found 1រោច Pisakh - return timestamp at midnight (start of BE year change day)
689
+ // BE year changes at 00:00 on this day
690
+ const timestamp = new Date(year, searchMonth - 1, searchDay, 0, 0, 0, 0).getTime();
691
+ visakhaBocheaCache[year] = timestamp;
692
+ return timestamp;
693
+ }
694
+ }
695
+ }
696
+ // Fallback if not found
697
+ const fallback = new Date(year, 3, 15, 0, 0, 0, 0).getTime();
698
+ visakhaBocheaCache[year] = fallback;
699
+ return fallback;
700
+ }
701
+ function gregorianToKhmerInternal(year, month, day, hour = 0, minute = 0, second = 0, isSearching = false) {
702
+ /**
703
+ * This follows the original momentkh algorithm exactly using JDN for tracking
704
+ */
705
+ // Epoch: January 1, 1900 = dayNumber 0 (១កើត), month index 1 (បុស្ស)
706
+ let epochJdn = gregorianToJulianDay(1900, 1, 1);
707
+ const targetJdn = gregorianToJulianDay(year, month, day);
708
+ let khmerMonth = 1; // បុស្ស
709
+ let khmerDayNumber = 0; // 0-29 format
710
+ let diffDays = targetJdn - epochJdn;
711
+ // Move epoch by full Khmer years
712
+ if (diffDays > 0) {
713
+ while (true) {
714
+ // Get Gregorian date of current epoch to calculate BE year
715
+ const epochGreg = julianDayToGregorian(epochJdn);
716
+ // Match original: use epochMoment.clone().add(1, 'year')
717
+ const nextYearBE = getMaybeBEYear(epochGreg.year + 1, epochGreg.month);
718
+ const daysInNextYear = getNumberOfDaysInKhmerYear(nextYearBE);
719
+ if (diffDays > daysInNextYear) {
720
+ diffDays -= daysInNextYear;
721
+ epochJdn += daysInNextYear;
722
+ }
723
+ else {
724
+ break;
725
+ }
726
+ }
727
+ }
728
+ else if (diffDays < 0) {
729
+ while (diffDays < 0) {
730
+ const epochGreg = julianDayToGregorian(epochJdn);
731
+ const currentYearBE = getMaybeBEYear(epochGreg.year, epochGreg.month);
732
+ const daysInCurrentYear = getNumberOfDaysInKhmerYear(currentYearBE);
733
+ diffDays += daysInCurrentYear;
734
+ epochJdn -= daysInCurrentYear;
735
+ }
736
+ }
737
+ // Move epoch by full Khmer months
738
+ while (diffDays > 0) {
739
+ const epochGreg = julianDayToGregorian(epochJdn);
740
+ const currentBE = getMaybeBEYear(epochGreg.year, epochGreg.month);
741
+ const daysInMonth = getNumberOfDaysInKhmerMonth(khmerMonth, currentBE);
742
+ if (diffDays > daysInMonth) {
743
+ diffDays -= daysInMonth;
744
+ epochJdn += daysInMonth;
745
+ khmerMonth = nextMonthOf(khmerMonth, currentBE);
746
+ }
747
+ else {
748
+ break;
749
+ }
750
+ }
751
+ // Add remaining days
752
+ khmerDayNumber = diffDays;
753
+ // Fix overflow (e.g., if month has only 29 days but we calculated 30)
754
+ const finalBE = getMaybeBEYear(year, month);
755
+ const totalDaysInMonth = getNumberOfDaysInKhmerMonth(khmerMonth, finalBE);
756
+ if (khmerDayNumber >= totalDaysInMonth) {
757
+ khmerDayNumber = khmerDayNumber % totalDaysInMonth;
758
+ khmerMonth = nextMonthOf(khmerMonth, finalBE);
759
+ }
760
+ // Convert dayNumber to day/moonPhase format
761
+ const khmerDayInfo = KhmerDate.fromDayNumber(khmerDayNumber);
762
+ // Calculate actual BE year
763
+ // The BE year changes on ១រោច ខែពិសាខ (1st waning day of Pisakh = dayNumber 15)
764
+ // Compare datetime (including hour/minute) against BE year transition datetime
765
+ let beYear;
766
+ if (isSearching) {
767
+ // During search, use simple approximation to avoid recursion
768
+ beYear = month <= 4 ? year + 543 : year + 544;
769
+ }
770
+ else {
771
+ // Normal mode: compare against exact BE year transition datetime (1រោច Pisakh at 00:00)
772
+ const inputTimestamp = new Date(year, month - 1, day, hour, minute, second).getTime();
773
+ const beYearTransitionTimestamp = getVisakhaBochea(year);
774
+ if (inputTimestamp >= beYearTransitionTimestamp) {
775
+ // On or after 1រោច Pisakh (new BE year)
776
+ beYear = year + 544;
777
+ }
778
+ else {
779
+ // Before 1រោច Pisakh (old BE year)
780
+ beYear = year + 543;
781
+ }
782
+ }
783
+ // Calculate additional info
784
+ let jsYear = beToJs(beYear);
785
+ let animalYearIndex = ((beYear + 4) % 12 + 12) % 12;
786
+ // Adjust Era and Animal Year based on Khmer New Year logic
787
+ // They should change at New Year, not wait for Visakha Bochea (which changes BE)
788
+ if (!isSearching) {
789
+ const newYearInfo = getNewYearFullInfo(year);
790
+ const inputTimestamp = new Date(year, month - 1, day, hour, minute, second).getTime();
791
+ const visakhaBocheaTimestamp = getVisakhaBochea(year);
792
+ // Animal Year changes at Moha Songkran (exact New Year time)
793
+ // Only apply manual increment if we are in the gap between New Year and Visakha Bochea
794
+ // (After Visakha Bochea, the BE year increments, so the formula based on BE automatically gives the new Animal Year)
795
+ if (inputTimestamp >= newYearInfo.newYearMoment.getTime() && inputTimestamp <= visakhaBocheaTimestamp) {
796
+ animalYearIndex = (animalYearIndex + 1) % 12;
797
+ }
798
+ // Era changes at Midnight of Date Lerng Sak (3rd or 4th day of NY)
799
+ if (inputTimestamp >= newYearInfo.lerngSakMoment.getTime() && inputTimestamp <= visakhaBocheaTimestamp) {
800
+ jsYear++;
801
+ }
802
+ }
803
+ const eraYearIndex = ((jsYear % 10) + 10) % 10;
804
+ const dayOfWeek = getDayOfWeek(year, month, day);
805
+ const khmerDate = new KhmerDate(khmerDayInfo.day, khmerDayInfo.moonPhase, khmerMonth, beYear);
806
+ return {
807
+ gregorian: { year, month, day, hour, minute, second, dayOfWeek },
808
+ khmer: {
809
+ day: khmerDayInfo.day,
810
+ moonPhase: khmerDayInfo.moonPhase,
811
+ moonPhaseName: MoonStatusNames[khmerDayInfo.moonPhase],
812
+ monthIndex: khmerMonth,
813
+ monthName: LunarMonthNames[khmerMonth],
814
+ beYear: beYear,
815
+ jsYear: jsYear,
816
+ animalYear: animalYearIndex,
817
+ animalYearName: AnimalYearNames[animalYearIndex],
818
+ eraYear: eraYearIndex,
819
+ eraYearName: EraYearNames[eraYearIndex],
820
+ dayOfWeek: dayOfWeek,
821
+ dayOfWeekName: WeekdayNames[dayOfWeek]
822
+ },
823
+ _khmerDateObj: khmerDate
824
+ };
825
+ }
826
+ function khmerToGregorian(day, moonPhase, monthIndex, beYear) {
827
+ // Validate input parameters
828
+ validateKhmerDate(day, moonPhase, monthIndex, beYear);
829
+ // Convert enums to numbers if needed
830
+ const moonPhaseNum = typeof moonPhase === 'number' ? moonPhase : moonPhase;
831
+ const monthIndexNum = typeof monthIndex === 'number' ? monthIndex : monthIndex;
832
+ // Convert BE year to approximate Gregorian year
833
+ const approxYear = beYear - 544;
834
+ // Search within a range around the approximate year
835
+ // Start from 2 years before to 2 years after to account for calendar differences
836
+ const startYear = approxYear - 2;
837
+ const endYear = approxYear + 2;
838
+ let candidates = [];
839
+ // Iterate through Gregorian dates to find all matches
840
+ for (let year = startYear; year <= endYear; year++) {
841
+ for (let month = 1; month <= 12; month++) {
842
+ const daysInMonth = getDaysInGregorianMonth(year, month);
843
+ for (let gDay = 1; gDay <= daysInMonth; gDay++) {
844
+ // For BE year transition day (1រោច Pisakh) and the day before (15កើត Pisakh),
845
+ // check multiple times during the day because BE year can change during this period
846
+ const isAroundBEYearChange = monthIndexNum === MonthIndex.Visakh &&
847
+ ((day === 15 && moonPhaseNum === MoonPhase.Waxing) || (day === 1 && moonPhaseNum === MoonPhase.Waning));
848
+ const timesToCheck = isAroundBEYearChange
849
+ ? [0, 6, 12, 18, 23] // Check at different hours
850
+ : [0]; // Normal case: just check at midnight
851
+ for (const hour of timesToCheck) {
852
+ const khmerResult = gregorianToKhmerInternal(year, month, gDay, hour, 0, 0, false);
853
+ // Check if it matches our target
854
+ if (khmerResult.khmer.beYear === beYear &&
855
+ khmerResult.khmer.monthIndex === monthIndexNum &&
856
+ khmerResult.khmer.day === day &&
857
+ khmerResult.khmer.moonPhase === moonPhaseNum) {
858
+ candidates.push({ year, month, day: gDay });
859
+ break; // Found a match for this date, no need to check other times
860
+ }
861
+ }
862
+ }
863
+ }
864
+ }
865
+ if (candidates.length === 0) {
866
+ throw new Error(`Could not find Gregorian date for Khmer date: ${day} ${moonPhaseNum === MoonPhase.Waxing ? 'កើត' : 'រោច'} month ${monthIndexNum} BE ${beYear}`);
867
+ }
868
+ // If multiple candidates found, prefer closest to approximate year
869
+ if (candidates.length > 1) {
870
+ // First, try to filter by year distance
871
+ const minDistance = Math.min(...candidates.map(c => Math.abs(c.year - approxYear)));
872
+ const closestCandidates = candidates.filter(c => Math.abs(c.year - approxYear) === minDistance);
873
+ // If we have a unique closest candidate, return it
874
+ if (closestCandidates.length === 1) {
875
+ return closestCandidates[0];
876
+ }
877
+ // If there are ties, prefer the one that matches at noon
878
+ const noonMatches = closestCandidates.filter(c => {
879
+ const noonCheck = gregorianToKhmerInternal(c.year, c.month, c.day, 12, 0, 0, false);
880
+ return noonCheck.khmer.beYear === beYear &&
881
+ noonCheck.khmer.monthIndex === monthIndexNum &&
882
+ noonCheck.khmer.day === day &&
883
+ noonCheck.khmer.moonPhase === moonPhaseNum;
884
+ });
885
+ if (noonMatches.length > 0) {
886
+ return noonMatches[0];
887
+ }
888
+ // Fall back to first closest candidate
889
+ return closestCandidates[0];
890
+ }
891
+ return candidates[0];
892
+ }
893
+ function getNewYearFullInfo(ceYear) {
894
+ if (newYearInfoCache[ceYear]) {
895
+ return newYearInfoCache[ceYear];
896
+ }
897
+ // Calculate using the standard algorithm first to get necessary info (like angsar for numberNewYearDay)
898
+ const jsYear = adToJs(ceYear);
899
+ let newYearInfo = getNewYearInfo(jsYear);
900
+ // Get Lerng Sak info
901
+ let bodithey = getBoditheyJs(jsYear);
902
+ const isAthikameasPrev = isAdhikameas(jsYear - 1);
903
+ const isChantrathimeasPrev = isChantrathimeas(jsYear - 1);
904
+ if (isAthikameasPrev && isChantrathimeasPrev) {
905
+ bodithey = (bodithey + 1) % 30;
906
+ }
907
+ // lunar DateLerngSak
908
+ const lunarDateLerngSak = {
909
+ day: bodithey >= 6 ? bodithey - 1 : bodithey,
910
+ month: bodithey >= 6 ? 4 : 5 // ចេត្រ or ពិសាខ
911
+ };
912
+ // Number of new year days
913
+ const numberNewYearDay = newYearInfo.newYearsDaySotins[0].angsar === 0 ? 4 : 3;
914
+ // Use April 17 as epoch and work backwards
915
+ const epochLerngSakGreg = { year: ceYear, month: 4, day: 17 };
916
+ // IMPORTANT: prevent recursion by passing isSearching=true (or any flag that skips Era check)
917
+ // gregorianToKhmerInternal(..., isSearching=true) uses simplified BE calc and skips Era check
918
+ const khEpoch = gregorianToKhmerInternal(ceYear, 4, 17, 12, 0, 0, true)._khmerDateObj;
919
+ // Calculate difference
920
+ const diffFromEpoch = ((khEpoch.monthIndex - 4) * 29 + khEpoch.getDayNumber()) -
921
+ ((lunarDateLerngSak.month - 4) * 29 + lunarDateLerngSak.day);
922
+ // Calculate days to subtract
923
+ const daysToSubtract = diffFromEpoch + numberNewYearDay - 1;
924
+ // Calculate new year date (Moha Songkran)
925
+ const epochJdn = gregorianToJulianDay(epochLerngSakGreg.year, epochLerngSakGreg.month, epochLerngSakGreg.day);
926
+ let newYearJdn = epochJdn - daysToSubtract;
927
+ // Override with cache if available
928
+ if (khNewYearMoments[ceYear]) {
929
+ const [datePart, timePart] = khNewYearMoments[ceYear].split(' ');
930
+ const [d, m, y] = datePart.split('-').map(Number);
931
+ const [hr, min] = timePart.split(':').map(Number);
932
+ // Update newYearInfo time
933
+ newYearInfo.timeOfNewYear = { hour: hr, minute: min };
934
+ // Update JDN based on cached date
935
+ newYearJdn = gregorianToJulianDay(y, m, d);
936
+ }
937
+ const newYearDate = julianDayToGregorian(newYearJdn);
938
+ const newYearMoment = new Date(newYearDate.year, newYearDate.month - 1, newYearDate.day, newYearInfo.timeOfNewYear.hour, newYearInfo.timeOfNewYear.minute);
939
+ // Calculate Lerng Sak Date (Midnight)
940
+ // Lerng Sak is the last day of NY celebration.
941
+ // Jdn = newYearJdn + (numberNewYearDay - 1)
942
+ const lerngSakJdn = newYearJdn + numberNewYearDay - 1;
943
+ const lerngSakDate = julianDayToGregorian(lerngSakJdn);
944
+ const lerngSakMoment = new Date(lerngSakDate.year, lerngSakDate.month - 1, lerngSakDate.day, 0, 0, 0); // Midnight
945
+ const result = {
946
+ newYearMoment,
947
+ lerngSakMoment,
948
+ newYearInfo: {
949
+ year: newYearDate.year,
950
+ month: newYearDate.month,
951
+ day: newYearDate.day,
952
+ hour: newYearInfo.timeOfNewYear.hour,
953
+ minute: newYearInfo.timeOfNewYear.minute
954
+ }
955
+ };
956
+ newYearInfoCache[ceYear] = result;
957
+ return result;
958
+ }
959
+ function getKhmerNewYear(ceYear) {
960
+ const info = getNewYearFullInfo(ceYear);
961
+ return info.newYearInfo;
962
+ }
963
+ // ============================================================================
964
+ // Formatting Functions
965
+ // ============================================================================
966
+ function format(khmerData, formatString) {
967
+ if (!formatString) {
968
+ // Default format
969
+ const { khmer } = khmerData;
970
+ const moonDay = `${khmer.day}${khmer.moonPhaseName}`;
971
+ return toKhmerNumeral(`ថ្ងៃ${khmer.dayOfWeekName} ${moonDay} ខែ${khmer.monthName} ឆ្នាំ${khmer.animalYearName} ${khmer.eraYearName} ពុទ្ធសករាជ ${khmer.beYear}`);
972
+ }
973
+ // Custom format
974
+ const formatRules = {
975
+ 'W': () => khmerData.khmer.dayOfWeekName,
976
+ 'w': () => WeekdayNamesShort[khmerData.gregorian.dayOfWeek],
977
+ 'd': () => khmerData.khmer.day,
978
+ 'D': () => (khmerData.khmer.day < 10 ? '0' : '') + khmerData.khmer.day,
979
+ 'n': () => MoonStatusShort[khmerData.khmer.moonPhase],
980
+ 'N': () => khmerData.khmer.moonPhaseName,
981
+ 'o': () => MoonDaySymbols[khmerData._khmerDateObj.getDayNumber()],
982
+ 'm': () => khmerData.khmer.monthName,
983
+ 'M': () => SolarMonthNames[khmerData.gregorian.month - 1],
984
+ 'a': () => khmerData.khmer.animalYearName,
985
+ 'e': () => khmerData.khmer.eraYearName,
986
+ 'b': () => khmerData.khmer.beYear,
987
+ 'c': () => khmerData.gregorian.year,
988
+ 'j': () => khmerData.khmer.jsYear
989
+ };
990
+ const regex = new RegExp(Object.keys(formatRules).join('|'), 'g');
991
+ const result = formatString.replace(regex, match => {
992
+ const value = formatRules[match]();
993
+ return toKhmerNumeral(String(value));
994
+ });
995
+ return result;
996
+ }
997
+ // ============================================================================
998
+ // Wrapper function for public API
999
+ function gregorianToKhmer(year, month, day, hour = 0, minute = 0, second = 0) {
1000
+ // Validate input parameters
1001
+ validateGregorianDate(year, month, day, hour, minute, second);
1002
+ return gregorianToKhmerInternal(year, month, day, hour, minute, second, false);
1003
+ }
1004
+ // ============================================================================
1005
+ // Public API
1006
+ // ============================================================================
1007
+ exports.momentkh = {
1008
+ // Conversion functions
1009
+ fromGregorian(year, month, day, hour = 0, minute = 0, second = 0) {
1010
+ return gregorianToKhmer(year, month, day, hour, minute, second);
1011
+ },
1012
+ fromKhmer(day, moonPhase, monthIndex, beYear) {
1013
+ return khmerToGregorian(day, moonPhase, monthIndex, beYear);
1014
+ },
1015
+ // New Year function
1016
+ getNewYear(ceYear) {
1017
+ return getKhmerNewYear(ceYear);
1018
+ },
1019
+ // Format function
1020
+ format(khmerData, formatString) {
1021
+ return format(khmerData, formatString);
1022
+ },
1023
+ // Utility for creating date from Date object
1024
+ fromDate(date) {
1025
+ // Validate Date object
1026
+ validateDateObject(date);
1027
+ return gregorianToKhmer(date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
1028
+ },
1029
+ // Convert Khmer to Date object
1030
+ toDate(day, moonPhase, monthIndex, beYear) {
1031
+ const greg = khmerToGregorian(day, moonPhase, monthIndex, beYear);
1032
+ return new Date(greg.year, greg.month - 1, greg.day);
1033
+ },
1034
+ // Constants export
1035
+ constants: {
1036
+ LunarMonths,
1037
+ LunarMonthNames,
1038
+ SolarMonthNames,
1039
+ AnimalYearNames,
1040
+ EraYearNames,
1041
+ WeekdayNames,
1042
+ MoonStatusNames
1043
+ },
1044
+ // Enums export for easier usage
1045
+ MoonPhase,
1046
+ MonthIndex,
1047
+ AnimalYear,
1048
+ EraYear,
1049
+ DayOfWeek
1050
+ };
1051
+ // Default export
1052
+ exports.default = exports.momentkh;