npdatetime 0.2.4

Astronomical calculator for Bikram Sambat calendar based on solar and lunar positions. High-performance Nepali (Bikram Sambat) datetime library with multi-language bindings
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
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
use crate::core::error::{NpdatetimeError, Result};
use std::fmt;

// Reference point: Start of BS 1975
pub const BS_EPOCH_YEAR: i32 = 1975;
pub const BS_EPOCH_AD: (i32, u8, u8) = (1918, 4, 13);

/// Month names in Nepali
pub const NEPALI_MONTHS: [&str; 12] = [
    "Baisakh", "Jestha", "Ashadh", "Shrawan", "Bhadra", "Ashwin", "Kartik", "Mangsir", "Poush",
    "Magh", "Falgun", "Chaitra",
];

/// Month names in Nepali (Devanagari)
pub const NEPALI_MONTHS_UNICODE: [&str; 12] = [
    "बैशाख",
    "जेष्ठ",
    "आषाढ",
    "श्रावण",
    "भाद्र",
    "आश्विन",
    "कार्तिक",
    "मंसिर",
    "पौष",
    "माघ",
    "फाल्गुन",
    "चैत्र",
];

/// Weekday names in Nepali
pub const NEPALI_WEEKDAYS: [&str; 7] = [
    "Aaitabaar",
    "Sombaar",
    "Mangalbaar",
    "Budhabaar",
    "Bihibaar",
    "Shukrabaar",
    "Shanibaar",
];

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct NepaliDate {
    pub year: i32,
    pub month: u8,
    pub day: u8,
}

impl NepaliDate {
    /// Creates a new Nepali date
    pub fn new(year: i32, month: u8, day: u8) -> Result<Self> {
        if !(1..=12).contains(&month) {
            return Err(NpdatetimeError::InvalidDate(format!(
                "Month must be between 1 and 12, got {}",
                month
            )));
        }

        let max_day = Self::days_in_month(year, month)?;
        if day < 1 || day > max_day {
            return Err(NpdatetimeError::InvalidDate(format!(
                "Day must be between 1 and {}, got {}",
                max_day, day
            )));
        }

        Ok(NepaliDate { year, month, day })
    }

    /// Returns the number of days in a given month
    pub fn days_in_month(year: i32, month: u8) -> Result<u8> {
        if !(1..=12).contains(&month) {
            return Err(NpdatetimeError::InvalidDate(format!(
                "Invalid month: {}",
                month
            )));
        }

        // Access the lookup data.
        // Note: For now, we'll keep the lookup logic here or in a dedicated lookup module.
        // In the final lib.rs, we'll probably have a way to access BS_MONTH_DATA.
        // For now, let's assume we'll use a trait or a global provided by lib.rs
        // (but that creates circular dependencies).
        // Let's keep it simple for now and move the data access to lib.rs or a dedicated lookup mod.

        #[cfg(feature = "lookup-tables")]
        if (1975..=2100).contains(&year) {
            return crate::lookup::get_days_in_month(year, month);
        }

        #[cfg(feature = "astronomical")]
        {
            let cal = crate::astronomical::calendar::BsCalendar::new();
            return Ok(cal.calculate_month_days(year, month));
        }

        #[allow(unreachable_code)]
        Err(NpdatetimeError::OutOfRange(format!(
            "Year {} is out of supported range (or no calendar provider feature enabled)",
            year
        )))
    }

    /// Converts Nepali date to Gregorian date (year, month, day)
    pub fn to_gregorian(&self) -> Result<(i32, u8, u8)> {
        let mut total_days = 0i64;

        for y in BS_EPOCH_YEAR..self.year {
            for m in 1..=12 {
                total_days += Self::days_in_month(y, m)? as i64;
            }
        }

        for m in 1..self.month {
            total_days += Self::days_in_month(self.year, m)? as i64;
        }

        total_days += (self.day - 1) as i64;

        let (mut year, mut month, mut day) = BS_EPOCH_AD;
        let mut days_to_add = total_days;

        while days_to_add > 0 {
            let days_in_current_month = gregorian_days_in_month(year, month);
            if days_to_add >= (days_in_current_month - day + 1) as i64 {
                days_to_add -= (days_in_current_month - day + 1) as i64;
                day = 1;
                month += 1;
                if month > 12 {
                    month = 1;
                    year += 1;
                }
            } else {
                day += days_to_add as u8;
                days_to_add = 0;
            }
        }

        Ok((year, month, day))
    }

    /// Creates a Nepali date from a Gregorian date
    pub fn from_gregorian(year: i32, month: u8, day: u8) -> Result<Self> {
        let total_days = gregorian_days_since_epoch(year, month, day, BS_EPOCH_AD)?;

        let mut remaining_days = total_days;
        let mut bs_year = BS_EPOCH_YEAR;
        let mut bs_month = 1u8;

        loop {
            let mut year_days = 0;
            for m in 1..=12 {
                year_days += Self::days_in_month(bs_year, m)? as i64;
            }

            if remaining_days >= year_days {
                remaining_days -= year_days;
                bs_year += 1;
            } else {
                break;
            }
        }

        while bs_month <= 12 {
            let month_days = Self::days_in_month(bs_year, bs_month)? as i64;
            if remaining_days >= month_days {
                remaining_days -= month_days;
                bs_month += 1;
            } else {
                break;
            }
        }

        let bs_day = (remaining_days + 1) as u8;
        Self::new(bs_year, bs_month, bs_day)
    }

    /// Returns the ordinal representation of the date (days since 1975-01-01 BS)
    /// 1975-01-01 BS is ordinal 1.
    pub fn to_ordinal(&self) -> i32 {
        let mut total_days = 0;

        for y in BS_EPOCH_YEAR..self.year {
            for m in 1..=12 {
                total_days += Self::days_in_month(y, m).unwrap_or(30) as i32;
            }
        }

        for m in 1..self.month {
            total_days += Self::days_in_month(self.year, m).unwrap_or(30) as i32;
        }

        total_days += self.day as i32;
        total_days
    }

    /// Creates a NepaliDate from an ordinal (days since 1975-01-01 BS)
    pub fn from_ordinal(ordinal: i32) -> Result<Self> {
        if ordinal < 1 {
            return Err(NpdatetimeError::InvalidDate(
                "Ordinal must be at least 1".to_string(),
            ));
        }

        let mut remaining_days = (ordinal - 1) as i64;
        let mut bs_year = BS_EPOCH_YEAR;
        let mut bs_month = 1u8;

        loop {
            let mut year_days = 0;
            for m in 1..=12 {
                year_days += Self::days_in_month(bs_year, m)? as i64;
            }

            if remaining_days >= year_days {
                remaining_days -= year_days;
                bs_year += 1;
            } else {
                break;
            }
        }

        while bs_month <= 12 {
            let month_days = Self::days_in_month(bs_year, bs_month)? as i64;
            if remaining_days >= month_days {
                remaining_days -= month_days;
                bs_month += 1;
            } else {
                break;
            }
        }

        let bs_day = (remaining_days + 1) as u8;
        Self::new(bs_year, bs_month, bs_day)
    }

    /// Returns today's date in Nepali calendar
    pub fn today() -> Result<Self> {
        use std::time::{SystemTime, UNIX_EPOCH};

        let duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();

        let days_since_unix_epoch = duration.as_secs() / 86400;
        let (year, month, day) = unix_epoch_to_gregorian(days_since_unix_epoch);

        Self::from_gregorian(year, month, day)
    }

    /// Returns the Nepali Fiscal Year for the date.
    /// In Nepal, the fiscal year starts on Shrawan 1.
    /// Returns a string like "2080/81"
    pub fn fiscal_year(&self) -> String {
        if self.month >= 4 {
            // Shrawan (4) or later
            format!("{}/{:02}", self.year, (self.year + 1) % 100)
        } else {
            // Before Shrawan
            format!("{}/{:02}", self.year - 1, self.year % 100)
        }
    }

    /// Returns the fiscal quarter (1-4)
    /// Q1: Shrawan, Bhadra, Ashwin
    /// Q2: Kartik, Mangsir, Poush
    /// Q3: Magh, Falgun, Chaitra
    /// Q4: Baisakh, Jestha, Ashadh
    pub fn fiscal_quarter(&self) -> u8 {
        match self.month {
            4..=6 => 1,
            7..=9 => 2,
            10..=12 => 3,
            1..=3 => 4,
            _ => 1, // Should not happen
        }
    }

    /// Formats the date as a string
    pub fn format(&self, format_str: &str) -> String {
        format_str
            .replace("%Y", &self.year.to_string())
            .replace("%m", &format!("{:02}", self.month))
            .replace("%d", &format!("{:02}", self.day))
            .replace("%B", NEPALI_MONTHS[(self.month - 1) as usize])
            .replace("%b", &NEPALI_MONTHS[(self.month - 1) as usize][..3])
    }

    /// Adds days to the date
    pub fn add_days(&self, days: i32) -> Result<Self> {
        let (g_year, g_month, g_day) = self.to_gregorian()?;
        let total_days = gregorian_to_days(g_year, g_month, g_day) + days as i64;
        let (new_year, new_month, new_day) = days_to_gregorian(total_days);
        Self::from_gregorian(new_year, new_month, new_day)
    }
}

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

// Gregorian helpers (keeping them here for now, could go to utils)

pub fn is_gregorian_leap_year(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

pub fn gregorian_days_in_month(year: i32, month: u8) -> u8 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            if is_gregorian_leap_year(year) {
                29
            } else {
                28
            }
        }
        _ => 0,
    }
}

pub fn gregorian_days_since_epoch(
    year: i32,
    month: u8,
    day: u8,
    epoch: (i32, u8, u8),
) -> Result<i64> {
    let (ey, em, ed) = epoch;

    if year < ey || (year == ey && month < em) || (year == ey && month == em && day < ed) {
        return Err(NpdatetimeError::OutOfRange(
            "Date is before the BS epoch".to_string(),
        ));
    }

    let mut total_days = 0i64;

    for y in ey..year {
        total_days += if is_gregorian_leap_year(y) { 366 } else { 365 };
    }

    for m in 1..em {
        total_days -= gregorian_days_in_month(ey, m) as i64;
    }
    total_days -= (ed - 1) as i64;

    for m in 1..month {
        total_days += gregorian_days_in_month(year, m) as i64;
    }
    total_days += (day - 1) as i64;

    Ok(total_days)
}

pub fn gregorian_to_days(year: i32, month: u8, day: u8) -> i64 {
    let mut days = 0i64;
    for y in 1..year {
        days += if is_gregorian_leap_year(y) { 366 } else { 365 };
    }
    for m in 1..month {
        days += gregorian_days_in_month(year, m) as i64;
    }
    days + day as i64
}

pub fn days_to_gregorian(mut days: i64) -> (i32, u8, u8) {
    let mut year = 1i32;
    loop {
        let year_days = if is_gregorian_leap_year(year) {
            366
        } else {
            365
        };
        if days > year_days {
            days -= year_days;
            year += 1;
        } else {
            break;
        }
    }
    let mut month = 1u8;
    while month <= 12 {
        let month_days = gregorian_days_in_month(year, month) as i64;
        if days > month_days {
            days -= month_days;
            month += 1;
        } else {
            break;
        }
    }
    (year, month, days as u8)
}

pub fn unix_epoch_to_gregorian(days_since_epoch: u64) -> (i32, u8, u8) {
    let base_days = gregorian_to_days(1970, 1, 1);
    let total_days = base_days + days_since_epoch as i64;
    days_to_gregorian(total_days)
}

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

    #[cfg(any(feature = "lookup-tables", feature = "astronomical"))]
    #[test]
    fn test_create_valid_date() {
        let date = NepaliDate::new(2077, 5, 19).unwrap();
        assert_eq!(date.year, 2077);
        assert_eq!(date.month, 5);
        assert_eq!(date.day, 19);
    }

    #[test]
    fn test_invalid_month() {
        assert!(NepaliDate::new(2077, 13, 1).is_err());
        assert!(NepaliDate::new(2077, 0, 1).is_err());
    }

    #[cfg(any(feature = "lookup-tables", feature = "astronomical"))]
    #[test]
    fn test_conversion_to_gregorian() {
        let bs_date = NepaliDate::new(2000, 1, 1).unwrap();
        let ad_date = bs_date.to_gregorian().unwrap();
        assert_eq!(ad_date, (1943, 4, 14));
    }

    #[cfg(any(feature = "lookup-tables", feature = "astronomical"))]
    #[test]
    fn test_conversion_from_gregorian() {
        let bs_date = NepaliDate::from_gregorian(1943, 4, 14).unwrap();
        assert_eq!(bs_date.year, 2000);
        assert_eq!(bs_date.month, 1);
        assert_eq!(bs_date.day, 1);
    }

    #[cfg(any(feature = "lookup-tables", feature = "astronomical"))]
    #[test]
    fn test_format() {
        let date = NepaliDate::new(2077, 5, 19).unwrap();
        assert_eq!(date.format("%Y-%m-%d"), "2077-05-19");
        assert_eq!(date.format("%d %B %Y"), "19 Bhadra 2077");
    }

    #[cfg(any(feature = "lookup-tables", feature = "astronomical"))]
    #[test]
    fn test_display() {
        let date = NepaliDate::new(2077, 5, 19).unwrap();
        assert_eq!(format!("{}", date), "2077-05-19");
    }

    #[cfg(any(feature = "lookup-tables", feature = "astronomical"))]
    #[test]
    fn test_add_days_within_month() {
        let date = NepaliDate::new(2077, 5, 10).unwrap();
        let new_date = date.add_days(5).unwrap();
        assert_eq!(new_date.year, 2077);
        assert_eq!(new_date.month, 5);
        assert_eq!(new_date.day, 15);
    }

    #[cfg(any(feature = "lookup-tables", feature = "astronomical"))]
    #[test]
    fn test_add_days_across_month() {
        // 2077 Bhadra (month 5) has 31 days
        let date = NepaliDate::new(2077, 5, 28).unwrap();
        let new_date = date.add_days(5).unwrap();
        assert_eq!(new_date.year, 2077);
        assert_eq!(new_date.month, 6); // Should move to Ashwin
    }

    #[cfg(any(feature = "lookup-tables", feature = "astronomical"))]
    #[test]
    fn test_add_days_across_year() {
        // 2077 Chaitra (month 12) has 31 days
        let date = NepaliDate::new(2077, 12, 30).unwrap();
        let new_date = date.add_days(5).unwrap();
        assert_eq!(new_date.year, 2078);
        assert_eq!(new_date.month, 1);
    }

    #[cfg(any(feature = "lookup-tables", feature = "astronomical"))]
    #[test]
    fn test_add_negative_days() {
        let date = NepaliDate::new(2077, 5, 19).unwrap();
        let new_date = date.add_days(-5).unwrap();
        assert_eq!(new_date.year, 2077);
        assert_eq!(new_date.month, 5);
        assert_eq!(new_date.day, 14);
    }

    #[cfg(any(feature = "lookup-tables", feature = "astronomical"))]
    #[test]
    fn test_add_days_round_trip() {
        let original = NepaliDate::new(2077, 5, 19).unwrap();
        let forward = original.add_days(100).unwrap();
        let back = forward.add_days(-100).unwrap();
        assert_eq!(original, back);
    }
}