junobuild_shared/day.rs
1use crate::types::utils::CalendarDate;
2use time::{Duration, OffsetDateTime};
3
4/// Converts a Unix timestamp (in nanoseconds) to an `OffsetDateTime`.
5///
6/// # Arguments
7/// - `timestamp`: A reference to a `u64` Unix timestamp in nanoseconds.
8///
9/// # Returns
10/// An `OffsetDateTime` representing the given timestamp.
11///
12/// # Panics
13/// Panics if the conversion to a timestamp fails, which can happen if the value
14/// represents a time outside the valid range that `OffsetDateTime` can represent.
15fn to_date(timestamp: &u64) -> OffsetDateTime {
16 let nanoseconds = *timestamp as i64;
17 let seconds = nanoseconds / 1_000_000_000;
18 let nanos_remainder = nanoseconds % 1_000_000_000;
19
20 OffsetDateTime::from_unix_timestamp(seconds).unwrap() + Duration::nanoseconds(nanos_remainder)
21}
22
23/// Returns the day of the year for a given timestamp.
24///
25/// # Arguments
26/// - `timestamp`: A reference to a `u64` Unix timestamp in nanoseconds.
27///
28/// # Returns
29/// The day of the year as `usize`, ranging from 1 to 366.
30pub fn day_of_the_year(timestamp: &u64) -> usize {
31 let ordinal = to_date(timestamp).ordinal();
32
33 ordinal as usize
34}
35
36/// Converts a Unix timestamp (in nanoseconds) to a `CalendarDate`.
37///
38/// # Arguments
39/// - `timestamp`: A reference to a `u64` Unix timestamp in nanoseconds.
40///
41/// # Returns
42/// A `CalendarDate` representing the date of the given timestamp.
43pub fn calendar_date(timestamp: &u64) -> CalendarDate {
44 CalendarDate::from(&to_date(timestamp).to_calendar_date())
45}