jdate 1.0.0

A library for converting between Gregorian and Jewish dates
Documentation
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
use chrono::{NaiveDate, Local, Datelike};
use std::fmt;

// The Epoch we use is the molad tohu (Day 1 = 1 Tishrei 1 = 7 September -3760)
// It is a theoretical time point 1 year before creation.


/// Rata Die day number
pub struct RD {
    pub rd: i32
}

/// Gregorian Date
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GDate {
    pub year: i32,
    pub month: u8, // 1 = Nisan, 13 = Adar2
    pub day: u8, // 1 - 30
}

/// Jewish Date
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct JDate {
    pub year: i32,
    pub month: u8, // 1 = Nisan, 13 = Adar2
    pub day: u8, // 1 - 30
}

impl GDate {
    pub fn new(year: i32, month: u8, day: u8) -> Option<GDate> {
        NaiveDate::from_ymd_opt(year, month as u32, day as u32)
            .map(|_| GDate{year: year, month: month, day: day})
    }

    pub fn today() -> GDate {
        let date = Local::now().date_naive();
        GDate{
            year:  date.year(),
            month: date.month() as u8,
            day:   date.day() as u8
        }
    }
}


impl JDate {
    /// Create a new JDate with year, month, day. If the date is invalid: None is returned.
    pub fn new(year: i32, month: u8, day: u8) -> Option<JDate> {
        match date_is_valid(year, month, day) {
            true  => Some(JDate{year: year, month: month, day: day}),
            false => None
        }
    }

    pub fn today() -> JDate {
        JDate::from(GDate::today())
    }

    /// Get the month as a string
    pub fn month_name(self: Self) -> &'static str {
        const NAMES: [&str; 13] = [
            "Nisan", "Iyar", "Sivan", "Tamuz", "Av", "Elul",
            "Tishrei", "Cheshvan", "Kislev", "Tevet", "Shvat", "Adar", "Adar2"];
        if self.month == 12 && is_leap_year(self.year) {
            return "Adar1"
        }
        return NAMES[self.month as usize - 1];

    }

    pub fn dafyomi(self: Self) -> (&'static str, u8) {
        let tractates = [
            ("Berachos",      63),
            ("Shabbos",      156),
            ("Eruvin",       104),
            ("Pesachim",     120),
            ("Shekalim",      21),
            ("Yoma",          87),
            ("Sukah",         55),
            ("Beitzah",       39),
            ("Rosh Hashanah", 34),
            ("Taanis",        30),
            ("Megilah",       31),
            ("Moed Katan",    28),
            ("Chagigah",      26),
            ("Yevamos",      121),
            ("Kesuvos",      111),
            ("Nedarim",       90),
            ("Nazir",         65),
            ("Sotah",         48),
            ("Gitin",         89),
            ("Kidushin",      81),
            ("Bava Kama",    118),
            ("Bava Metzia",  118),
            ("Bava Basra",   175),
            ("Sanhedrin",    112),
            ("Makos",         23),
            ("Shevuos",       48),
            ("Avodah Zarah",  75),
            ("Horayos",       13),
            ("Zevachim",     119),
            ("Menachos",     109),
            ("Chulin",       141),
            ("Bechoros",      60),
            ("Erchin",        33),
            ("Temurah",       33),
            ("Kerisus",       27),
            ("Meilah",        36),
            ("Nidah",         72),
        ];
        let rd = RD::from(self).rd;
        let mut day = (rd - 37).rem_euclid(2711);
        for (trac, pages) in tractates.iter() {
            if day <= pages - 1 {
                return (trac, (day+2) as u8);
            }
            day -= pages;
        }
        return ("", 0);
    }

    pub fn omer(self: Self) -> u8 {
        let day = self.day;
        let month = self.month;
        if month == 1 && day >= 16 {
            return day - 15;
        } else if month == 2 {
            return day + 15;
        } else if month == 3 && day < 6 {
            return day + 44;
        } else {
            return 0;
        }
    }
}

impl fmt::Display for GDate {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:0>4}-{:0>2}-{:0>2}", self.year, self.month, self.day)
    }
}

impl fmt::Display for JDate {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:0>4}-{}-{:0>2}", self.year, self.month_name(), self.day)
    }
}

impl From<RD> for JDate {
    /// JDate from RD
    fn from(rd: RD) -> JDate {
        let ed = rd.rd + 1373428; // days since epoch
        let mut year = ed * 100 / 36525;
        while year_start(year) < ed {year += 1;}
        while year_start(year) > ed {year -= 1;}
        let mut days = year_start(year);
        let days_in_month = year_months(year);
        let mut month = 7;
        loop {
            let length = days_in_month[month] as i32;
            if days + length > ed {break}
            month += 1;
            if month == 14 {month = 1}
            if month == 7 {unreachable!()}
            days += length;
        }
        return JDate{
            year: year,
            month: month as u8,
            day: (ed-days+1) as u8
        };
    }
}

impl From<JDate> for RD {
    /// RD from JDate
    fn from(j: JDate) -> RD {
        let mut ed = year_start(j.year) - 1;
        let days_in_month = year_months(j.year);
        let mut month: u8 = 7;
        loop {
            let length = days_in_month[month as usize];
            if month == j.month {
                ed += j.day as i32;
                break;
            }
            ed += length as i32;
            month += 1;
            if month == 14 {month = 1}
            if month == 7 {unreachable!()}
        }
        RD{rd: ed - 1373428}
    }
}

impl From<RD> for GDate {
    /// GDate from RD
    fn from(rd: RD) -> GDate {
        let date = NaiveDate::from_epoch_days(rd.rd - 719163).unwrap();
        GDate{
            year: date.year(),
            month: date.month() as u8,
            day: date.day() as u8
        }
    }
}

impl From<GDate> for RD {
    /// RD from GDate
    fn from(g: GDate) -> RD {
        RD{
            rd: NaiveDate::from_ymd_opt(g.year, g.month as u32, g.day as u32)
                .unwrap()
                .to_epoch_days()
                + 719163
        }
    }
}

impl From<GDate> for JDate {
    /// Convert Gregorian Date to JDate
    fn from(d: GDate) -> JDate {
        JDate::from(RD::from(d))
    }
}

impl From<JDate> for GDate {
    /// Convert JDate to Gregorian Date
    fn from(j: JDate) -> Self {
        GDate::from(RD::from(j))

    }
}

/// Determine if the Jewish year is a leap year
pub fn is_leap_year(year: i32) -> bool {
    match year % 19 {
        0|3|6|8|11|14|17 => true,
        _ => false
    }
}

/// Determine if the Jewish date is valid
pub fn date_is_valid(year: i32, month: u8, day: u8) -> bool {
    if month < 1 || month > 13 || day < 1 || day > 30 {
        return false;
    }
    if month == 13 {
        return day <= 29 && is_leap_year(year);
    }
    if day == 30 {
        return match month {
            1|3|5|7|11 => true,
            2|4|6|10 => false,
            12 => is_leap_year(year),
            8 => {
                year_length(year) % 10 == 5 // complete year (355 or 385)
            },
            9 => {
                year_length(year) % 10 >= 4 // complete or regular year (354, 355, 384 or 385)
            },
            _ => unreachable!()
        }
    }
    true
}

/// Calculates the molad of the given year
///
/// returns the number of chalakim since the epoch
pub fn molad(year: i32) -> i64 {
    let parts_month = (29*24+12)*1080+793;
    let parts_year  = 12 * parts_month;
    let parts_lyear = 13 * parts_month;
    let parts_cycle = 12 * parts_year + 7 * parts_lyear;
    let total_cycles  = (year-1).div_euclid(19);
    let year_in_cycle = (year-1).rem_euclid(19);
    let mut molad: i64 = (24+5)*1080+204; // molad tohu
    molad += total_cycles as i64 * parts_cycle as i64;
    for year in 0..year_in_cycle {
        if is_leap_year(year+1) {
            molad += parts_lyear as i64;
        } else {
            molad += parts_year as i64;
        }
    }
    return molad;
}

/// Calculates the molad of the given year
///
/// returns the days since epoch, hours (after 6pm), and parts (out of 1080
/// chalakim)
pub fn molad_components(year: i32) -> (i32, u8, u16) {
    let molad = molad(year);
    return ((molad.div_euclid(1080*24)) as i32,
            (molad.div_euclid(1080).rem_euclid(24)) as u8,
            (molad.rem_euclid(1080)) as u16);
}

/// Print molad in a friendly format
pub fn molad_print(year: i32) {
    let (day, hour, parts) = molad_components(year);
    let day = day % 7;
    let hour = (hour + 18) % 24;
    let minute = parts / 18;
    let parts = parts % 18;

    let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    let day_str = days[day as usize];
    println!("Molad {year}: {day_str} {hour:0>2}:{minute:0>2} and {parts:>2} \
              chalakim");
}

/// Calculates what day (since epoch) the year starts
pub fn year_start(year: i32) -> i32 {
    let molad = molad(year);
    let day   = molad.div_euclid(1080*24) as i32;
    let parts = molad.rem_euclid(1080*24) as i32;
    let mut rosh = day;
    // first rule: if molad is after noon (18 hours after 6pm), Rosh Hashana is
    // postponed 1 day
    if parts >= 18*1080 {
        rosh += 1;
    }
    // second rule: lo ADU
    if rosh % 7 == 0 || rosh % 7 == 3 || rosh % 7 == 5 {
        rosh += 1;
    }
    // third rule: Ga-Ta-RaD
    if !is_leap_year(year) && day % 7 == 2 && parts >= 9*1080+204 {
        rosh = day+2;
    }
    // fourth rule: Be-TU-TeKaPoT
    if is_leap_year(year-1) && day % 7 == 1 && parts >= 15*1080+589 {
        rosh = day+1;
    }
    return rosh;
}

/// Calculates the number of days in the Jewish year
pub fn year_length(year: i32) -> i32 {
    let rosh1 = year_start(year);
    let rosh2 = year_start(year+1);
    return rosh2-rosh1;
}

/// Returns a list of months with the number of days in them
pub fn year_months(year: i32) -> [u8; 14] {
    let mut days_in_month = [0, 30, 29, 30, 29, 30, 29,     // Nisan - Elul
                                30, 29, 30, 29, 30, 29, 0]; // Tishrei - Adar2
    if is_leap_year(year) {
        days_in_month[12] = 30; days_in_month[13] = 29;
    }
    let length = year_length(year);
    if length % 10 == 3 {
        // Deficient year
        days_in_month[9] = 29;
    }
    if length % 10 == 5 {
        // Complete year
        days_in_month[8] = 30;
    }
    return days_in_month;
}

#[cfg(test)]
mod tests {
    use super::*;

    // helpers

    fn gdate(year: i32, month: u8, day: u8) -> GDate {
        GDate::new(year, month, day).unwrap()
    }

    fn jdate(year: i32, month: u8, day: u8) -> JDate {
        JDate::new(year, month, day).unwrap()
    }

    fn check_roundtrip(g: GDate, j: JDate) {
        assert_eq!(JDate::from(g), j);
        assert_eq!(GDate::from(j), g);
    }


    #[test]
    fn test_molad_year() {
        assert_eq!(molad_components(1), (1, 5, 204));
        assert_eq!(molad_components(5785), (2112590, 9, 391));
    }

    #[test]
    fn test_leap_year() {
        assert!(is_leap_year(5700));
        assert!(!is_leap_year(5701));
        assert!(!is_leap_year(5702));
        assert!(is_leap_year(5703));
        assert!(is_leap_year(5782));
        assert!(!is_leap_year(5783));
        assert!(is_leap_year(5784));
        assert!(!is_leap_year(5785));
        assert!(!is_leap_year(5786));
        assert!(is_leap_year(5787));
    }

    #[test]
    fn test_jdate_new() {
        // valid dates
        assert!(JDate::new(5785,  1,  1).is_some());
        assert!(JDate::new(5784, 12, 30).is_some());
        assert!(JDate::new(5784, 13,  1).is_some());
        assert!(JDate::new(5786,  9, 30).is_some());
        assert!(JDate::new(5787,  9, 30).is_some());
        // invalid dates
        assert!(JDate::new(5785, 13,  1).is_none());
        assert!(JDate::new(5785,  0,  1).is_none());
        assert!(JDate::new(5785, 14,  1).is_none());
        assert!(JDate::new(5785,  1,  0).is_none());
        assert!(JDate::new(5785,  1, 31).is_none());
        assert!(JDate::new(5785,  2, 30).is_none());
        assert!(JDate::new(5785, 12, 30).is_none());
        assert!(JDate::new(5785, 13, 30).is_none());
        assert!(JDate::new(5781,  8, 30).is_none());
        assert!(JDate::new(5781,  9, 30).is_none());
        assert!(JDate::new(5786,  8, 30).is_none());
    }

    #[test]
    fn test_roundtrip() {
        check_roundtrip(gdate(    1, 1,  1), jdate(3761, 10, 18));
        check_roundtrip(gdate(-3760, 9,  7), jdate(   1,  7,  1));
        check_roundtrip(gdate(2024, 12, 31), jdate(5785,  9, 30));
        check_roundtrip(gdate(2025,  1,  1), jdate(5785, 10,  1));
        check_roundtrip(gdate(2025,  2,  1), jdate(5785, 11,  3));
        check_roundtrip(gdate(2025,  3,  1), jdate(5785, 12,  1));
        check_roundtrip(gdate(2024,  2, 10), jdate(5784, 12,  1));
        check_roundtrip(gdate(2024,  3, 11), jdate(5784, 13,  1));
        check_roundtrip(gdate(2024,  4,  9), jdate(5784,  1,  1));
        check_roundtrip(gdate(2024, 10,  2), jdate(5784,  6, 29));
        check_roundtrip(gdate(2024, 10,  3), jdate(5785,  7,  1));
    }

    #[test]
    fn test_dafyomi() {
        assert_eq!(jdate(5772,  5, 15).dafyomi(), ("Berachos", 2));
        assert_eq!(jdate(5780, 10,  8).dafyomi(), ("Berachos", 2));
        assert_eq!(jdate(5780, 12, 11).dafyomi(), ("Berachos", 64));
        assert_eq!(jdate(5780, 12, 12).dafyomi(), ("Shabbos", 2));
        assert_eq!(jdate(5784,  7,  6).dafyomi(), ("Kidushin", 39));
        assert_eq!(jdate(5787,  3,  2).dafyomi(), ("Nidah", 73));
    }

    #[test]
    fn test_omer() {
        assert_eq!(jdate(5785,  1, 15).omer(), 0);
        assert_eq!(jdate(5785,  1, 16).omer(), 1);
        assert_eq!(jdate(5785,  1, 30).omer(), 15);
        assert_eq!(jdate(5785,  2,  1).omer(), 16);
        assert_eq!(jdate(5785,  2, 29).omer(), 44);
        assert_eq!(jdate(5785,  3,  1).omer(), 45);
        assert_eq!(jdate(5785,  3,  5).omer(), 49);
        assert_eq!(jdate(5785,  3,  6).omer(), 0);
        assert_eq!(jdate(5785,  4,  1).omer(), 0);
        assert_eq!(jdate(5785,  1,  1).omer(), 0);
    }
}