Skip to main content

system_time/
fn.rs

1use super::*;
2
3/// Reads the current system duration since the Unix epoch.
4///
5/// # Returns
6///
7/// - `Duration` - The elapsed duration since `UNIX_EPOCH`.
8#[inline(always)]
9fn now_duration() -> Duration {
10    SystemTime::now()
11        .duration_since(UNIX_EPOCH)
12        .unwrap_or_default()
13}
14
15/// Writes a two-digit decimal integer (`00`..=`99`) into `buf` starting at `pos`.
16///
17/// # Arguments
18///
19/// - `&mut [u8]` - The destination ASCII byte buffer.
20/// - `usize` - The starting write index.
21/// - `u64` - The value in `0..=99` to format.
22#[inline(always)]
23fn write_two_digits(buf: &mut [u8], pos: usize, value: u64) {
24    let idx: usize = (value as usize) * 2;
25    buf[pos] = DIGIT_PAIRS[idx];
26    buf[pos + 1] = DIGIT_PAIRS[idx + 1];
27}
28
29/// Writes a three-digit decimal integer (`000`..=`999`) into `buf` starting at `pos`.
30///
31/// # Arguments
32///
33/// - `&mut [u8]` - The destination ASCII byte buffer.
34/// - `usize` - The starting write index.
35/// - `u64` - The value in `0..=999` to format.
36#[inline(always)]
37fn write_three_digits(buf: &mut [u8], pos: usize, value: u64) {
38    let hundreds: u8 = (value / 100) as u8;
39    buf[pos] = ASCII_ZERO + hundreds;
40    write_two_digits(buf, pos + 1, value % 100);
41}
42
43/// Writes a four-digit decimal integer (`0000`..=`9999`) into `buf` starting at `pos`.
44///
45/// # Arguments
46///
47/// - `&mut [u8]` - The destination ASCII byte buffer.
48/// - `usize` - The starting write index.
49/// - `u64` - The value in `0..=9999` to format.
50#[inline(always)]
51fn write_four_digits(buf: &mut [u8], pos: usize, value: u64) {
52    write_two_digits(buf, pos, value / 100);
53    write_two_digits(buf, pos + 2, value % 100);
54}
55
56/// Writes `YYYY-MM-DD HH:MM:SS` into the first 19 bytes of `buf`.
57///
58/// # Arguments
59///
60/// - `&mut [u8]` - The destination ASCII byte buffer (at least 19 bytes).
61/// - `u64` - The 4-digit year (`0..=9999`).
62/// - `u64` - The month (`1..=12`).
63/// - `u64` - The day (`1..=31`).
64/// - `u64` - The hour (`0..=23`).
65/// - `u64` - The minute (`0..=59`).
66/// - `u64` - The second (`0..=59`).
67#[inline(always)]
68fn write_datetime_prefix(
69    buf: &mut [u8],
70    year: u64,
71    month: u64,
72    day: u64,
73    hour: u64,
74    minute: u64,
75    second: u64,
76) {
77    write_four_digits(buf, 0, year);
78    buf[4] = DATE_DASH;
79    write_two_digits(buf, 5, month);
80    buf[7] = DATE_DASH;
81    write_two_digits(buf, 8, day);
82    buf[10] = DATE_TIME_SEP;
83    write_two_digits(buf, 11, hour);
84    buf[13] = TIME_COLON;
85    write_two_digits(buf, 14, minute);
86    buf[16] = TIME_COLON;
87    write_two_digits(buf, 17, second);
88}
89
90/// Converts a stack ASCII byte buffer into a `String` in a single exact-sized allocation.
91///
92/// # Arguments
93///
94/// - `&[u8]` - Valid ASCII bytes.
95///
96/// # Returns
97///
98/// - `String` - Newly allocated string containing those bytes.
99#[inline(always)]
100fn ascii_bytes_to_string(bytes: &[u8]) -> String {
101    let vec: Vec<u8> = bytes.to_vec();
102    unsafe { String::from_utf8_unchecked(vec) }
103}
104
105/// Gets the time zone offset from the system environment variable.
106///
107/// This function retrieves the `LANG` environment variable and attempts to
108/// parse it into a `Lang` value. If the variable is not set or cannot be
109/// parsed, it defaults to `Lang::default()`.
110///
111/// # Returns
112///
113/// - `Lang` - The corresponding `Lang` value based on the `LANG` environment variable.
114#[inline(always)]
115pub fn from_env_var() -> Lang {
116    env::var_os(LANG_ENV_VAR)
117        .and_then(|value: OsString| Lang::from_bytes(value.as_encoded_bytes()))
118        .unwrap_or_default()
119}
120
121/// Determines if a year is a leap year.
122///
123/// # Arguments
124///
125/// - `u64` - The year to check.
126///
127/// # Returns
128///
129/// - `bool` - Whether the year is a leap year.
130#[inline(always)]
131pub fn is_leap_year(year: u64) -> bool {
132    (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400)
133}
134
135/// Gets the current time, including the date and time.
136///
137/// # Returns
138///
139/// - `String` - The formatted time as `YYYY-MM-DD HH:MM:SS`
140pub fn time() -> String {
141    let duration: Duration = now_duration();
142    let total_seconds: u64 = duration.as_secs();
143    let (year, month, day): (u64, u64, u64) = compute_date(total_seconds / SECONDS_PER_DAY);
144    let remaining_seconds: u64 = total_seconds % SECONDS_PER_DAY;
145    let timezone_offset: u64 = from_env_var().value();
146    let hour: u64 = ((remaining_seconds + timezone_offset) / SECONDS_PER_HOUR) % HOURS_PER_DAY;
147    let minute: u64 = (remaining_seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
148    let second: u64 = remaining_seconds % SECONDS_PER_MINUTE;
149    if year <= MAX_FOUR_DIGIT_YEAR {
150        let mut buf: [u8; 19] = [0u8; 19];
151        write_datetime_prefix(&mut buf, year, month, day, hour, minute, second);
152        return ascii_bytes_to_string(&buf);
153    }
154    let mut date_time: String = String::with_capacity(24);
155    let _: fmt::Result = write!(
156        &mut date_time,
157        "{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}"
158    );
159    date_time
160}
161
162/// Gets the current day, without the time.
163///
164/// # Returns
165///
166/// - `String` - The formatted date as `YYYY-MM-DD`
167pub fn date() -> String {
168    let total_seconds: u64 = now_duration().as_secs();
169    let (year, month, day): (u64, u64, u64) = compute_date(total_seconds / SECONDS_PER_DAY);
170    if year <= MAX_FOUR_DIGIT_YEAR {
171        let mut buf: [u8; 10] = [0u8; 10];
172        write_four_digits(&mut buf, 0, year);
173        buf[4] = DATE_DASH;
174        write_two_digits(&mut buf, 5, month);
175        buf[7] = DATE_DASH;
176        write_two_digits(&mut buf, 8, day);
177        return ascii_bytes_to_string(&buf);
178    }
179    let mut date_time: String = String::with_capacity(16);
180    let _: fmt::Result = write!(&mut date_time, "{year:04}-{month:02}-{day:02}");
181    date_time
182}
183
184/// Computes the year, month, and day from days since Unix epoch (1970-01-01).
185///
186/// # Arguments
187///
188/// - `u64` - Number of days since Unix epoch.
189///
190/// # Returns
191///
192/// - `(u64, u64, u64)` - Tuple containing year, month and day.
193#[inline(always)]
194pub fn compute_date(days_since_epoch: u64) -> (u64, u64, u64) {
195    if let Some(z) = days_since_epoch.checked_add(HINNANT_EPOCH_OFFSET) {
196        let era: u64 = z / DAYS_PER_ERA;
197        let doe: u64 = z - era * DAYS_PER_ERA;
198        let yoe: u64 = (doe - doe / DAYS_PER_4_YEARS + doe / DAYS_PER_100_YEARS
199            - doe / DAYS_PER_ERA_MINUS_1)
200            / DAYS_PER_YEAR;
201        let y: u64 = yoe + era * YEARS_PER_ERA;
202        let doy: u64 = doe - (DAYS_PER_YEAR * yoe + yoe / 4 - yoe / 100);
203        let mp: u64 = (5 * doy + 2) / 153;
204        let day: u64 = doy - (153 * mp + 2) / 5 + 1;
205        let month: u64 = if mp < 10 { mp + 3 } else { mp - 9 };
206        let year: u64 = y + u64::from(month <= 2);
207        return (year, month, day);
208    }
209    let z: u128 = days_since_epoch as u128 + HINNANT_EPOCH_OFFSET as u128;
210    let era: u128 = z / DAYS_PER_ERA as u128;
211    let doe: u128 = z - era * DAYS_PER_ERA as u128;
212    let yoe: u128 = (doe - doe / DAYS_PER_4_YEARS as u128 + doe / DAYS_PER_100_YEARS as u128
213        - doe / DAYS_PER_ERA_MINUS_1 as u128)
214        / DAYS_PER_YEAR as u128;
215    let y: u128 = yoe + era * YEARS_PER_ERA as u128;
216    let doy: u128 = doe - (DAYS_PER_YEAR as u128 * yoe + yoe / 4 - yoe / 100);
217    let mp: u128 = (5 * doy + 2) / 153;
218    let day: u64 = (doy - (153 * mp + 2) / 5 + 1) as u64;
219    let month: u64 = if mp < 10 { mp + 3 } else { mp - 9 } as u64;
220    let year: u64 = (y + u128::from(month <= 2)) as u64;
221    (year, month, day)
222}
223
224/// Gets the current date and time in GMT format.
225///
226/// # Returns
227///
228/// - `String` - The current date and time in GMT format.
229pub fn gmt() -> String {
230    let timestamp: u64 = now_duration().as_secs();
231    let days_since_epoch: u64 = timestamp / SECONDS_PER_DAY;
232    let seconds_of_day: u64 = timestamp % SECONDS_PER_DAY;
233    let hours: u64 = seconds_of_day / SECONDS_PER_HOUR;
234    let minutes: u64 = (seconds_of_day % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
235    let seconds: u64 = seconds_of_day % SECONDS_PER_MINUTE;
236    let (year, month, day): (u64, u64, u64) = compute_date(days_since_epoch);
237    let weekday: usize = ((days_since_epoch + 4) % 7) as usize;
238    let day_name: &[u8; 3] = &DAYS[weekday];
239    let month_name: &[u8; 3] = &MONTHS[month as usize - 1];
240    if year <= MAX_FOUR_DIGIT_YEAR {
241        let mut buf: [u8; 29] = [0u8; 29];
242        buf[0..3].copy_from_slice(day_name);
243        buf[3] = GMT_COMMA;
244        buf[4] = DATE_TIME_SEP;
245        write_two_digits(&mut buf, 5, day);
246        buf[7] = DATE_TIME_SEP;
247        buf[8..11].copy_from_slice(month_name);
248        buf[11] = DATE_TIME_SEP;
249        write_four_digits(&mut buf, 12, year);
250        buf[16] = DATE_TIME_SEP;
251        write_two_digits(&mut buf, 17, hours);
252        buf[19] = TIME_COLON;
253        write_two_digits(&mut buf, 20, minutes);
254        buf[22] = TIME_COLON;
255        write_two_digits(&mut buf, 23, seconds);
256        buf[25..29].copy_from_slice(&GMT_SUFFIX);
257        return ascii_bytes_to_string(&buf);
258    }
259    let day_str: &str = unsafe { from_utf8_unchecked(day_name) };
260    let month_str: &str = unsafe { from_utf8_unchecked(month_name) };
261    format!("{day_str}, {day:02} {month_str} {year} {hours:02}:{minutes:02}:{seconds:02} GMT")
262}
263
264/// Gets the current year.
265///
266/// # Returns
267///
268/// - `u64` - The current year
269#[inline(always)]
270pub fn year() -> u64 {
271    compute_date(now_duration().as_secs() / SECONDS_PER_DAY).0
272}
273
274/// Gets the current month.
275///
276/// # Returns
277///
278/// - `u64` - The current month (1-12)
279#[inline(always)]
280pub fn month() -> u64 {
281    compute_date(now_duration().as_secs() / SECONDS_PER_DAY).1
282}
283
284/// Gets the current day.
285///
286/// # Returns
287///
288/// - `u64` - The current day of the month
289#[inline(always)]
290pub fn day() -> u64 {
291    compute_date(now_duration().as_secs() / SECONDS_PER_DAY).2
292}
293
294/// Gets the current hour.
295///
296/// # Returns
297///
298/// - `u64` - The current hour (0-23)
299#[inline(always)]
300pub fn hour() -> u64 {
301    let remaining_seconds: u64 = now_duration().as_secs() % SECONDS_PER_DAY;
302    let timezone_offset: u64 = from_env_var().value();
303    ((remaining_seconds + timezone_offset) / SECONDS_PER_HOUR) % HOURS_PER_DAY
304}
305
306/// Gets the current minute.
307///
308/// # Returns
309///
310/// - `u64` - The current minute (0-59)
311#[inline(always)]
312pub fn minute() -> u64 {
313    (now_duration().as_secs() % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE
314}
315
316/// Gets the current second.
317///
318/// # Returns
319///
320/// - `u64` - The current second (0-59)
321#[inline(always)]
322pub fn second() -> u64 {
323    now_duration().as_secs() % SECONDS_PER_MINUTE
324}
325
326/// Gets the current timestamp in milliseconds.
327///
328/// # Returns
329///
330/// - `u64` - The current timestamp in milliseconds since Unix epoch
331#[inline(always)]
332pub fn millis() -> u64 {
333    now_duration().subsec_millis() as u64
334}
335
336/// Gets the current timestamp in microseconds.
337///
338/// # Returns
339///
340/// - `u64` - The current timestamp in microseconds since Unix epoch
341#[inline(always)]
342pub fn micros() -> u64 {
343    now_duration().subsec_micros() as u64
344}
345
346/// Calculates the current year, month, day, hour, minute, second, millisecond and microsecond.
347///
348/// # Returns
349///
350/// - `(u64, u64, u64, u64, u64, u64, u64, u64)` - Tuple containing:
351///   - Year
352///   - Month
353///   - Day
354///   - Hour (0-23)
355///   - Minute (0-59)
356///   - Second (0-59)
357///   - Milliseconds in current second
358///   - Microseconds in current second
359#[inline(always)]
360pub fn calculate_time() -> (u64, u64, u64, u64, u64, u64, u64, u64) {
361    let duration: Duration = now_duration();
362    let total_seconds: u64 = duration.as_secs();
363    let nanoseconds: u64 = duration.subsec_nanos() as u64;
364    let milliseconds: u64 = nanoseconds / 1_000_000;
365    let microseconds: u64 = nanoseconds / 1_000;
366    let (year, month, day): (u64, u64, u64) = compute_date(total_seconds / SECONDS_PER_DAY);
367    let remaining_seconds: u64 = total_seconds % SECONDS_PER_DAY;
368    let timezone_offset: u64 = from_env_var().value();
369    let hour: u64 = ((remaining_seconds + timezone_offset) / SECONDS_PER_HOUR) % HOURS_PER_DAY;
370    let minute: u64 = (remaining_seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
371    let second: u64 = remaining_seconds % SECONDS_PER_MINUTE;
372    (
373        year,
374        month,
375        day,
376        hour,
377        minute,
378        second,
379        milliseconds,
380        microseconds,
381    )
382}
383
384/// Gets the current time with milliseconds, including the date and time.
385///
386/// # Returns
387///
388/// - `String` - The formatted time as `YYYY-MM-DD HH:MM:SS.sss`
389pub fn time_millis() -> String {
390    let (year, month, day, hour, minute, second, millisecond, _): (
391        u64,
392        u64,
393        u64,
394        u64,
395        u64,
396        u64,
397        u64,
398        u64,
399    ) = calculate_time();
400    if year <= MAX_FOUR_DIGIT_YEAR {
401        let mut buf: [u8; 23] = [0u8; 23];
402        write_datetime_prefix(&mut buf, year, month, day, hour, minute, second);
403        buf[19] = TIME_DOT;
404        write_three_digits(&mut buf, 20, millisecond);
405        return ascii_bytes_to_string(&buf);
406    }
407    let mut date_time: String = String::with_capacity(28);
408    let _: fmt::Result = write!(
409        &mut date_time,
410        "{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}.{millisecond:03}"
411    );
412    date_time
413}
414
415/// Gets the current time with microseconds, including the date and time.
416///
417/// # Returns
418///
419/// - `String` - The formatted time as `YYYY-MM-DD HH:MM:SS.ssssss`
420pub fn time_micros() -> String {
421    let (year, month, day, hour, minute, second, _, microseconds): (
422        u64,
423        u64,
424        u64,
425        u64,
426        u64,
427        u64,
428        u64,
429        u64,
430    ) = calculate_time();
431    if year <= MAX_FOUR_DIGIT_YEAR {
432        let mut buf: [u8; 26] = [0u8; 26];
433        write_datetime_prefix(&mut buf, year, month, day, hour, minute, second);
434        buf[19] = TIME_DOT;
435        write_three_digits(&mut buf, 20, microseconds / 1_000);
436        write_three_digits(&mut buf, 23, microseconds % 1_000);
437        return ascii_bytes_to_string(&buf);
438    }
439    let mut date_time: String = String::with_capacity(32);
440    let _: fmt::Result = write!(
441        &mut date_time,
442        "{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}.{microseconds:06}"
443    );
444    date_time
445}
446
447/// Gets the current timestamp in seconds since Unix epoch.
448///
449/// # Returns
450///
451/// - `u64` - The current timestamp in seconds
452#[inline(always)]
453pub fn timestamp() -> u64 {
454    let timezone_offset: u64 = from_env_var().value();
455    now_duration().as_secs().saturating_add(timezone_offset)
456}
457
458/// Gets the current timestamp in milliseconds since Unix epoch.
459///
460/// # Returns
461///
462/// - `u64` - The current timestamp in milliseconds
463#[inline(always)]
464pub fn timestamp_millis() -> u64 {
465    let timezone_offset: u64 = from_env_var().value();
466    let duration: Duration = now_duration();
467    (duration.as_secs().saturating_add(timezone_offset)) * 1000 + duration.subsec_millis() as u64
468}
469
470/// Gets the current timestamp in microseconds since Unix epoch.
471///
472/// # Returns
473///
474/// - `u64` - The current timestamp in microseconds
475#[inline(always)]
476pub fn timestamp_micros() -> u64 {
477    let timezone_offset: u64 = from_env_var().value();
478    let duration: Duration = now_duration();
479    (duration.as_secs().saturating_add(timezone_offset)) * 1_000_000
480        + duration.subsec_micros() as u64
481}