-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhdate.go
More file actions
655 lines (589 loc) · 17.9 KB
/
Copy pathhdate.go
File metadata and controls
655 lines (589 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
// Package hdate converts between Hebrew and Gregorian dates.
//
// It also includes functions for calculating personal anniversaries
// (Yahrzeit, Birthday) according to the Hebrew calendar.
//
// See also https://en.wikipedia.org/wiki/Rata_Die
package hdate
// Hebcal - A Jewish Calendar Generator
// Copyright (c) 2022 Michael J. Radwin
// Derived from original C version, Copyright (C) 1994-2004 Danny Sadinoff
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/hebcal/greg"
)
// An HMonth specifies a Hebrew month of the year (Nisan = 1, Tishrei = 7, ...).
type HMonth int
const (
// Nissan / ניסן
Nisan HMonth = 1 + iota
// Iyyar / אייר
Iyyar
// Sivan / סיון
Sivan
// Tammuz (sometimes Tamuz) / תמוז
Tamuz
// Av / אב
Av
// Elul / אלול
Elul
// Tishrei / תִשְׁרֵי
Tishrei
// Cheshvan / חשון
Cheshvan
// Kislev / כסלו
Kislev
// Tevet / טבת
Tevet
// Sh'vat / שבט
Shvat
// Adar or Adar Rishon / אדר
Adar1
// Adar Sheini (only on leap years) / אדר ב׳
Adar2
)
var longMonthNames = []string{
"",
"Nisan",
"Iyyar",
"Sivan",
"Tammuz",
"Av",
"Elul",
"Tishrei",
"Cheshvan",
"Kislev",
"Tevet",
"Sh'vat",
"Adar I",
"Adar II",
}
var heAdar = [2]string{"אַדָר", "אדר"}
// heMonthNames is indexed by HMonth; element 0 is unused. The two strings are
// the nikud and no-nikud ("he-x-NoNikud") spellings.
var heMonthNames = [Adar2 + 1][2]string{
Adar1: {"אַדָר א׳", "אדר א׳"},
Adar2: {"אַדָר ב׳", "אדר ב׳"},
Av: {"אָב", "אב"},
Cheshvan: {"חֶשְׁוָן", "חשון"},
Elul: {"אֱלוּל", "אלול"},
Iyyar: {"אִיָיר", "אייר"},
Kislev: {"כִּסְלֵו", "כסלו"},
Nisan: {"נִיסָן", "ניסן"},
Shvat: {"שְׁבָט", "שבט"},
Sivan: {"סִיוָן", "סיון"},
Tamuz: {"תַּמּוּז", "תמוז"},
Tevet: {"טֵבֵת", "טבת"},
Tishrei: {"תִשְׁרֵי", "תשרי"},
}
// String returns the English name of the month ("Nisan", "Iyyar", ...).
func (m HMonth) String() string {
if Nisan <= m && m <= Adar2 {
return longMonthNames[m]
}
return "%!HMonth(" + strconv.Itoa(int(m)) + ")"
}
// HDate represents a Hebrew date.
//
// To keep things simple, HDate represents just a day, month, and year.
//
// Although Hebrew dates begin at sunset, HDate does not attempt
// to represent any concept of the time of day. For halachic times,
// see the Zmanim interface.
type HDate struct {
year int // Hebrew year
month HMonth // Hebrew month (1-13)
day int // Hebrew day of month (1-30)
abs int64 // R.D. absolute date
}
// Epoch is the Hebrew Calendar epoch using R.D. Rata Die numbers
const Epoch int64 = -1373428
// Avg year length in the cycle (19 solar years with 235 lunar months)
const avgHebrewYearDays float64 = 365.24682220597794
// IsLeapYear returns true if Hebrew year is a leap year.
func IsLeapYear(year int) bool {
return (1+year*7)%19 < 7
}
// MonthsInYear returns the number of months in this Hebrew year
// (either 12 or 13 depending on leap year).
func MonthsInYear(year int) int {
if IsLeapYear(year) {
return 13
}
return 12
}
// DaysInYear computes the number of days in the Hebrew year.
//
// The year can be 353, 354, 355, 383, 384 or 385 days long.
func DaysInYear(year int) int {
return int(elapsedDays(year+1) - elapsedDays(year))
}
// LongCheshvan returns true if Cheshvan is long (30 days) in Hebrew year.
func LongCheshvan(year int) bool {
return DaysInYear(year)%10 == 5
}
// ShortKislev returns true if Kislev is short (29 days) in Hebrew year.
func ShortKislev(year int) bool {
return DaysInYear(year)%10 == 3
}
// DaysInMonth returns the number of days in Hebrew month in a given year (29 or 30).
func DaysInMonth(month HMonth, year int) int {
return daysInMonth(yearType(DaysInYear(year)), month)
}
// yearInfo returns the elapsed days of a Hebrew year together with its year
// type, sharing the lookup of the year's start and end between them. The
// conversion routines need both, and computing them separately would consult
// elapsedDays three times instead of twice.
func yearInfo(year int) (elapsed int64, t int) {
elapsed = elapsedDays(year)
return elapsed, yearType(int(elapsedDays(year+1) - elapsed))
}
// edCache memoizes elapsedDays for the practical Hebrew year range.
// Each slot is written at most once with a deterministic value; atomic
// access keeps it race-free at the same cost as a plain load on x86/arm.
// Years outside [edCacheMin, edCacheMax] fall through to recompute.
const (
edCacheMin = 5000
edCacheMax = 6999
)
var edCache [edCacheMax - edCacheMin + 1]int32
// elapsedDays returns the number of days from the sunday prior to the start
// of the Hebrew calendar to the mean conjunction of Tishrei in Hebrew year.
func elapsedDays(year int) int64 {
if year >= edCacheMin && year <= edCacheMax {
idx := year - edCacheMin
if n := atomic.LoadInt32(&edCache[idx]); n != 0 {
return int64(n)
}
v := elapsedDays0(year)
atomic.StoreInt32(&edCache[idx], int32(v))
return v
}
return elapsedDays0(year)
}
func elapsedDays0(year int) int64 {
prevYear := int64(year) - 1
mElapsed := 235*(prevYear/19) + // Months in complete 19 year lunar (Metonic) cycles so far
12*(prevYear%19) + // Regular months in this cycle
(((prevYear%19)*7 + 1) / 19) // Leap months this cycle
pElapsed := 204 + 793*(mElapsed%1080)
hElapsed := 5 +
12*mElapsed +
793*(mElapsed/1080) +
(pElapsed / 1080)
parts := (pElapsed % 1080) + 1080*(hElapsed%24)
day := 1 + 29*mElapsed + (hElapsed / 24)
altDay := day
if (parts >= 19440) ||
(((day % 7) == 2) && (parts >= 9924) && !IsLeapYear(year)) ||
(((day % 7) == 1) && (parts >= 16789) && IsLeapYear(int(prevYear))) {
altDay = day + 1
}
if altDay%7 == 0 || altDay%7 == 3 || altDay%7 == 5 {
return altDay + 1
}
return altDay
}
// ToRD converts Hebrew date to R.D. (Rata Die) fixed days.
// R.D. 1 is the imaginary date Monday, January 1, 1 on the Gregorian Calendar.
//
// Note also that R.D. = Julian Date − 1,721,424.5
//
// https://en.wikipedia.org/wiki/Rata_Die
func ToRD(year int, month HMonth, day int) int64 {
elapsed, t := yearInfo(year)
return Epoch + elapsed + monthOffset(t, month) + int64(day) - 1
}
// New creates a new HDate from year, Hebrew month, and day of month.
//
// Panics if Hebrew year is less than 1, if Hebrew month
// is not in the range [Tishrei..Adar2], or if Hebrew day
// is not in the range [1..30]
func New(year int, month HMonth, day int) HDate {
hd, err := newHDate(year, month, day)
if err != nil {
panic(err.Error())
}
return hd
}
// newHDate is New without the panic, for callers such as UnmarshalJSON that
// are handed untrusted input and must report bad values as an error.
func newHDate(year int, month HMonth, day int) (HDate, error) {
if year < 1 {
return HDate{}, fmt.Errorf("invalid Hebrew year %d", year)
}
if month == Adar2 && !IsLeapYear(year) {
month = Adar1
}
if month == Adar2+1 {
month = Nisan
}
if month < Nisan || month > Adar2 {
return HDate{}, errors.New("invalid Hebrew Month " + month.String())
}
elapsed, t := yearInfo(year)
if day < 1 || day > daysInMonth(t, month) {
return HDate{}, fmt.Errorf("invalid Hebrew day %d", day)
}
abs := Epoch + elapsed + monthOffset(t, month) + int64(day) - 1
return HDate{year: year, month: month, day: day, abs: abs}, nil
}
func newYear(year int) int64 {
return Epoch + elapsedDays(year)
}
// FromRD converts absolute Rata Die days to Hebrew date.
//
// Panics if rataDie is before the Hebrew epoch.
func FromRD(rataDie int64) HDate {
if rataDie <= Epoch {
panic(fmt.Sprintf("invalid R.D. date %d", rataDie))
}
// Estimate the year from the mean year length, then correct. The estimate
// is off by at most a year or so, and rataDie > Epoch guarantees that year
// 1 always starts on or before rataDie, so the search cannot run away.
year := int(float64(rataDie-Epoch) / avgHebrewYearDays)
if year < 1 {
year = 1
}
for year > 1 && newYear(year) > rataDie {
year--
}
for newYear(year+1) <= rataDie {
year++
}
elapsed, t := yearInfo(year)
dayOfYear := int(rataDie - (Epoch + elapsed)) // 0-based
month := HMonth(monthByDayOfYear[t][dayOfYear])
day := dayOfYear - int(monthOffsetTab[t][month]) + 1
return HDate{year: year, month: month, day: day, abs: rataDie}
}
// FromGregorian creates an HDate from Gregorian year, month and day.
func FromGregorian(year int, month time.Month, day int) HDate {
rataDie := greg.ToRD(year, month, day)
return FromRD(rataDie)
}
// FromProlepticGregorian creates an HDate from Gregorian year, month and day,
// using the Proleptic Gregorian calendar.
func FromProlepticGregorian(year int, month time.Month, day int) HDate {
rataDie := greg.ProlepticToRD(year, month, day)
return FromRD(rataDie)
}
// FromTime creates an HDate from a Time object. Hours, minutes and seconds are ignored.
func FromTime(t time.Time) HDate {
year, month, day := t.Date()
rataDie := greg.ToRD(year, month, day)
return FromRD(rataDie)
}
// Abs converts Hebrew date to R.D. (Rata Die) fixed days.
//
// R.D. 1 is the imaginary date Monday, January 1, 1 on the Gregorian Calendar.
func (hd HDate) Abs() int64 {
return hd.abs
}
// Day returns the day of month (1-30) of hd.
func (hd HDate) Day() int {
return hd.day
}
// Month returns the Hebrew month of hd.
func (hd HDate) Month() HMonth {
return hd.month
}
// Year returns the Hebrew year of hd.
func (hd HDate) Year() int {
return hd.year
}
// DaysInMonth returns the number of days in this date's month (29 or 30).
func (hd HDate) DaysInMonth() int {
return DaysInMonth(hd.Month(), hd.Year())
}
// Greg converts this Hebrew Date to Gregorian year, month and day.
func (hd HDate) Greg() (int, time.Month, int) {
return greg.FromRD(hd.Abs())
}
// ProlepticGreg converts this Hebrew Date to Proleptic Gregorian year, month and day.
func (hd HDate) ProlepticGreg() (int, time.Month, int) {
return greg.ProlepticFromRD(hd.Abs())
}
// Gregorian converts this Hebrew Date to a Gregorian time object.
//
// Hours, minutes and seconds are set to 0, and timezone is set to UTC.
func (hd HDate) Gregorian() time.Time {
year, month, day := hd.Greg()
return time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
}
// Weekday returns the day of the week specified by hd.
func (hd HDate) Weekday() time.Weekday {
abs := hd.Abs()
return time.Weekday(((abs % 7) + 7) % 7)
}
// Prev returns the previous Hebrew date.
func (hd HDate) Prev() HDate {
return FromRD(hd.Abs() - 1)
}
// Next returns the next Hebrew date.
func (hd HDate) Next() HDate {
return FromRD(hd.Abs() + 1)
}
// IsLeapYear returns true if this HDate occurs during a Hebrew leap year.
func (hd HDate) IsLeapYear() bool {
return IsLeapYear(hd.Year())
}
// MonthName returns a string representation of the month name.
//
// If locale is "he", returns Hebrew (e.g. "תִשְׁרֵי", "שְׁבָט", "אַדָר ב׳")
//
// Otherwise returns an English transliteration
// (e.g. "Tishrei", "Sh'vat", "Adar II").
func (hd HDate) MonthName(locale string) string {
month := hd.Month()
isAdar := month == Adar1 && !hd.IsLeapYear()
// EqualFold avoids the allocation that strings.ToLower makes on every call.
idx := -1
switch {
case strings.EqualFold(locale, "he"):
idx = 0
case strings.EqualFold(locale, "he-x-nonikud"):
idx = 1
}
if idx >= 0 && Nisan <= month && month <= Adar2 {
if isAdar {
return heAdar[idx]
}
return heMonthNames[month][idx]
}
if isAdar {
return "Adar"
}
return month.String()
}
// String returns a string representation of the Hebrew date
// in English transliteration (e.g. "15 Cheshvan 5769").
func (hd HDate) String() string {
// Formatted into a stack buffer so only the result string is allocated.
var buf [32]byte
b := strconv.AppendInt(buf[:0], int64(hd.Day()), 10)
b = append(b, ' ')
b = append(b, hd.MonthName("en")...)
b = append(b, ' ')
b = strconv.AppendInt(b, int64(hd.Year()), 10)
return string(b)
}
// ErrMonthName is returned by MonthFromName when the string cannot be parsed
// as a Hebrew month name. Test for it with errors.Is.
var ErrMonthName = errors.New("unable to parse month name")
// adarRegex matches the suffix that disambiguates "Adar I" / "Adar Rishon"
// from "Adar II" / "Adar Sheini" in MonthFromName.
var adarRegex = regexp.MustCompile("(?i)(1|[^i]i|a|א)(׳?)$")
// MonthFromName parses a Hebrew month string name to determine the month number.
//
// With the exception of Adar 1/Adar 2, Hebrew months are unique to their second letter.
//
// N Nisan (November?)
// I Iyyar
// E Elul
// C Cheshvan
// K Kislev
// Si Sh Sivan, Shvat
// Ta Ti Te Tamuz, Tishrei, Tevet
// Av Ad Av, Adar
//
// אב אד אי אל אב אדר אייר אלול
// ח חשון
// ט טבת
// כ כסלו
// נ ניסן
// ס סיון
// ש שבט
// תמ תש תמוז תשרי
//
// Adar1, Adar 1, Adar I, אדר א׳
// Adar2, Adar 2, Adar II, אדר ב׳
func MonthFromName(monthName string) (HMonth, error) {
// Only the first two runes are ever examined, so decode just those rather
// than allocating a lowercased copy and a []rune of the whole string.
r0, size := utf8.DecodeRuneInString(monthName)
if size == 0 {
return 0, ErrMonthName
}
var r1 rune
if size < len(monthName) {
r1, _ = utf8.DecodeRuneInString(monthName[size:])
}
r0, r1 = toLowerASCII(r0), toLowerASCII(r1)
switch r0 {
case 'n', 'נ':
if r1 == 'o' {
break // this catches "november"
}
return Nisan, nil
case 'i':
return Iyyar, nil
case 'e':
return Elul, nil
case 'c', 'ח':
return Cheshvan, nil
case 'k', 'כ':
return Kislev, nil
case 's':
switch r1 {
case 'i':
return Sivan, nil
case 'h':
return Shvat, nil
}
case 't':
switch r1 {
case 'a':
return Tamuz, nil
case 'i':
return Tishrei, nil
case 'e':
return Tevet, nil
}
case 'a':
switch r1 {
case 'v':
return Av, nil
case 'd':
if adarRegex.MatchString(monthName) {
return Adar1, nil
}
return Adar2, nil // else assume sheini
}
case 'ס':
return Sivan, nil
case 'ט':
return Tevet, nil
case 'ש':
return Shvat, nil
case 'א':
switch r1 {
case 'ב':
return Av, nil
case 'ד':
if adarRegex.MatchString(monthName) {
return Adar1, nil
}
return Adar2, nil // else assume sheini
case 'י':
return Iyyar, nil
case 'ל':
return Elul, nil
}
case 'ת':
switch r1 {
case 'מ':
return Tamuz, nil
case 'ש':
return Tishrei, nil
}
}
return 0, ErrMonthName
}
// toLowerASCII lowercases a rune if it is an ASCII letter. Hebrew is caseless,
// so this covers every alphabet MonthFromName accepts.
func toLowerASCII(r rune) rune {
if 'A' <= r && r <= 'Z' {
return r + ('a' - 'A')
}
return r
}
// DayOnOrBefore returns the R.D. of the given day of the week on or
// before rataDie.
//
// Applying DayOnOrBefore to d+6 gives us the dayOfWeek on or after an
// absolute day rataDie.
//
// Similarly, applying it to d+3 gives the dayOfWeek nearest to
// rataDie, applying it to d-1 gives the dayOfWeek previous to
// rataDie, and applying it to d+7 gives the dayOfWeek following rataDie.
func DayOnOrBefore(dayOfWeek time.Weekday, rataDie int64) int64 {
// Go's % truncates toward zero, so it must be floored by hand: R.D.
// numbers are negative before the common era, and a truncated remainder
// there would return a day *after* rataDie.
rem := (rataDie - int64(dayOfWeek)) % 7
if rem < 0 {
rem += 7
}
return rataDie - rem
}
func onOrBefore(dayOfWeek time.Weekday, rataDie int64) HDate {
return FromRD(DayOnOrBefore(dayOfWeek, rataDie))
}
// Before returns an HDate representing the dayOfWeek before
// the Hebrew date specified by hd.
func (hd HDate) Before(dayOfWeek time.Weekday) HDate {
return onOrBefore(dayOfWeek, hd.Abs()-1)
}
// OnOrBefore returns an HDate corresponding to the dayOfWeek on or before
// the Hebrew date specified by hd.
func (hd HDate) OnOrBefore(dayOfWeek time.Weekday) HDate {
return onOrBefore(dayOfWeek, hd.Abs())
}
// Nearest returns an HDate representing the nearest dayOfWeek to
// the Hebrew date specified by hd.
func (hd HDate) Nearest(dayOfWeek time.Weekday) HDate {
return onOrBefore(dayOfWeek, hd.Abs()+3)
}
// OnOrAfter returns an HDate corresponding to the dayOfWeek on or after
// the Hebrew date specified by hd.
func (hd HDate) OnOrAfter(dayOfWeek time.Weekday) HDate {
return onOrBefore(dayOfWeek, hd.Abs()+6)
}
// After returns an HDate corresponding to the dayOfWeek after
// the Hebrew date specified by hd.
func (hd HDate) After(dayOfWeek time.Weekday) HDate {
return onOrBefore(dayOfWeek, hd.Abs()+7)
}
type hdJSON struct {
Year int `json:"hy"` // Hebrew year
Month string `json:"hm"` // Hebrew month ("Kislev", "Adar I", ...)
Day int `json:"hd"` // Hebrew day of month (1-30)
}
// MarshalJSON implements the json.Marshaler interface.
func (hd HDate) MarshalJSON() ([]byte, error) {
tmp := hdJSON{
Year: hd.year,
Month: hd.MonthName("en"),
Day: hd.day,
}
return json.Marshal(tmp)
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (hd *HDate) UnmarshalJSON(b []byte) error {
var tmp hdJSON
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
month, err := MonthFromName(tmp.Month)
if err != nil {
return err
}
parsed, err := newHDate(tmp.Year, month, tmp.Day)
if err != nil {
return err
}
*hd = parsed
return nil
}