system-time 11.0.0

A library for fetching the current time based on the system's locale settings.
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
use super::*;

/// Reads the current system duration since the Unix epoch.
///
/// # Returns
///
/// - `Duration` - The elapsed duration since `UNIX_EPOCH`.
#[inline(always)]
fn now_duration() -> Duration {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
}

/// Writes a two-digit decimal integer (`00`..=`99`) into `buf` starting at `pos`.
///
/// # Arguments
///
/// - `&mut [u8]` - The destination ASCII byte buffer.
/// - `usize` - The starting write index.
/// - `u64` - The value in `0..=99` to format.
#[inline(always)]
fn write_two_digits(buf: &mut [u8], pos: usize, value: u64) {
    let idx: usize = (value as usize) * 2;
    buf[pos] = DIGIT_PAIRS[idx];
    buf[pos + 1] = DIGIT_PAIRS[idx + 1];
}

/// Writes a three-digit decimal integer (`000`..=`999`) into `buf` starting at `pos`.
///
/// # Arguments
///
/// - `&mut [u8]` - The destination ASCII byte buffer.
/// - `usize` - The starting write index.
/// - `u64` - The value in `0..=999` to format.
#[inline(always)]
fn write_three_digits(buf: &mut [u8], pos: usize, value: u64) {
    let hundreds: u8 = (value / 100) as u8;
    buf[pos] = ASCII_ZERO + hundreds;
    write_two_digits(buf, pos + 1, value % 100);
}

/// Writes a four-digit decimal integer (`0000`..=`9999`) into `buf` starting at `pos`.
///
/// # Arguments
///
/// - `&mut [u8]` - The destination ASCII byte buffer.
/// - `usize` - The starting write index.
/// - `u64` - The value in `0..=9999` to format.
#[inline(always)]
fn write_four_digits(buf: &mut [u8], pos: usize, value: u64) {
    write_two_digits(buf, pos, value / 100);
    write_two_digits(buf, pos + 2, value % 100);
}

/// Writes `YYYY-MM-DD HH:MM:SS` into the first 19 bytes of `buf`.
///
/// # Arguments
///
/// - `&mut [u8]` - The destination ASCII byte buffer (at least 19 bytes).
/// - `u64` - The 4-digit year (`0..=9999`).
/// - `u64` - The month (`1..=12`).
/// - `u64` - The day (`1..=31`).
/// - `u64` - The hour (`0..=23`).
/// - `u64` - The minute (`0..=59`).
/// - `u64` - The second (`0..=59`).
#[inline(always)]
fn write_datetime_prefix(
    buf: &mut [u8],
    year: u64,
    month: u64,
    day: u64,
    hour: u64,
    minute: u64,
    second: u64,
) {
    write_four_digits(buf, 0, year);
    buf[4] = DATE_DASH;
    write_two_digits(buf, 5, month);
    buf[7] = DATE_DASH;
    write_two_digits(buf, 8, day);
    buf[10] = DATE_TIME_SEP;
    write_two_digits(buf, 11, hour);
    buf[13] = TIME_COLON;
    write_two_digits(buf, 14, minute);
    buf[16] = TIME_COLON;
    write_two_digits(buf, 17, second);
}

/// Converts a stack ASCII byte buffer into a `String` in a single exact-sized allocation.
///
/// # Arguments
///
/// - `&[u8]` - Valid ASCII bytes.
///
/// # Returns
///
/// - `String` - Newly allocated string containing those bytes.
#[inline(always)]
fn ascii_bytes_to_string(bytes: &[u8]) -> String {
    let vec: Vec<u8> = bytes.to_vec();
    unsafe { String::from_utf8_unchecked(vec) }
}

/// Gets the time zone offset from the system environment variable.
///
/// This function retrieves the `LANG` environment variable and attempts to
/// parse it into a `Lang` value. If the variable is not set or cannot be
/// parsed, it defaults to `Lang::default()`.
///
/// # Returns
///
/// - `Lang` - The corresponding `Lang` value based on the `LANG` environment variable.
#[inline(always)]
pub fn from_env_var() -> Lang {
    env::var_os(LANG_ENV_VAR)
        .and_then(|value: OsString| Lang::from_bytes(value.as_encoded_bytes()))
        .unwrap_or_default()
}

/// Determines if a year is a leap year.
///
/// # Arguments
///
/// - `u64` - The year to check.
///
/// # Returns
///
/// - `bool` - Whether the year is a leap year.
#[inline(always)]
pub fn is_leap_year(year: u64) -> bool {
    (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400)
}

/// Gets the current time, including the date and time.
///
/// # Returns
///
/// - `String` - The formatted time as `YYYY-MM-DD HH:MM:SS`
pub fn time() -> String {
    let duration: Duration = now_duration();
    let total_seconds: u64 = duration.as_secs();
    let (year, month, day): (u64, u64, u64) = compute_date(total_seconds / SECONDS_PER_DAY);
    let remaining_seconds: u64 = total_seconds % SECONDS_PER_DAY;
    let timezone_offset: u64 = from_env_var().value();
    let hour: u64 = ((remaining_seconds + timezone_offset) / SECONDS_PER_HOUR) % HOURS_PER_DAY;
    let minute: u64 = (remaining_seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
    let second: u64 = remaining_seconds % SECONDS_PER_MINUTE;
    if year <= MAX_FOUR_DIGIT_YEAR {
        let mut buf: [u8; 19] = [0u8; 19];
        write_datetime_prefix(&mut buf, year, month, day, hour, minute, second);
        return ascii_bytes_to_string(&buf);
    }
    let mut date_time: String = String::with_capacity(24);
    let _: fmt::Result = write!(
        &mut date_time,
        "{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}"
    );
    date_time
}

/// Gets the current day, without the time.
///
/// # Returns
///
/// - `String` - The formatted date as `YYYY-MM-DD`
pub fn date() -> String {
    let total_seconds: u64 = now_duration().as_secs();
    let (year, month, day): (u64, u64, u64) = compute_date(total_seconds / SECONDS_PER_DAY);
    if year <= MAX_FOUR_DIGIT_YEAR {
        let mut buf: [u8; 10] = [0u8; 10];
        write_four_digits(&mut buf, 0, year);
        buf[4] = DATE_DASH;
        write_two_digits(&mut buf, 5, month);
        buf[7] = DATE_DASH;
        write_two_digits(&mut buf, 8, day);
        return ascii_bytes_to_string(&buf);
    }
    let mut date_time: String = String::with_capacity(16);
    let _: fmt::Result = write!(&mut date_time, "{year:04}-{month:02}-{day:02}");
    date_time
}

/// Computes the year, month, and day from days since Unix epoch (1970-01-01).
///
/// # Arguments
///
/// - `u64` - Number of days since Unix epoch.
///
/// # Returns
///
/// - `(u64, u64, u64)` - Tuple containing year, month and day.
#[inline(always)]
pub fn compute_date(days_since_epoch: u64) -> (u64, u64, u64) {
    if let Some(z) = days_since_epoch.checked_add(HINNANT_EPOCH_OFFSET) {
        let era: u64 = z / DAYS_PER_ERA;
        let doe: u64 = z - era * DAYS_PER_ERA;
        let yoe: u64 = (doe - doe / DAYS_PER_4_YEARS + doe / DAYS_PER_100_YEARS
            - doe / DAYS_PER_ERA_MINUS_1)
            / DAYS_PER_YEAR;
        let y: u64 = yoe + era * YEARS_PER_ERA;
        let doy: u64 = doe - (DAYS_PER_YEAR * yoe + yoe / 4 - yoe / 100);
        let mp: u64 = (5 * doy + 2) / 153;
        let day: u64 = doy - (153 * mp + 2) / 5 + 1;
        let month: u64 = if mp < 10 { mp + 3 } else { mp - 9 };
        let year: u64 = y + u64::from(month <= 2);
        return (year, month, day);
    }
    let z: u128 = days_since_epoch as u128 + HINNANT_EPOCH_OFFSET as u128;
    let era: u128 = z / DAYS_PER_ERA as u128;
    let doe: u128 = z - era * DAYS_PER_ERA as u128;
    let yoe: u128 = (doe - doe / DAYS_PER_4_YEARS as u128 + doe / DAYS_PER_100_YEARS as u128
        - doe / DAYS_PER_ERA_MINUS_1 as u128)
        / DAYS_PER_YEAR as u128;
    let y: u128 = yoe + era * YEARS_PER_ERA as u128;
    let doy: u128 = doe - (DAYS_PER_YEAR as u128 * yoe + yoe / 4 - yoe / 100);
    let mp: u128 = (5 * doy + 2) / 153;
    let day: u64 = (doy - (153 * mp + 2) / 5 + 1) as u64;
    let month: u64 = if mp < 10 { mp + 3 } else { mp - 9 } as u64;
    let year: u64 = (y + u128::from(month <= 2)) as u64;
    (year, month, day)
}

/// Gets the current date and time in GMT format.
///
/// # Returns
///
/// - `String` - The current date and time in GMT format.
pub fn gmt() -> String {
    let timestamp: u64 = now_duration().as_secs();
    let days_since_epoch: u64 = timestamp / SECONDS_PER_DAY;
    let seconds_of_day: u64 = timestamp % SECONDS_PER_DAY;
    let hours: u64 = seconds_of_day / SECONDS_PER_HOUR;
    let minutes: u64 = (seconds_of_day % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
    let seconds: u64 = seconds_of_day % SECONDS_PER_MINUTE;
    let (year, month, day): (u64, u64, u64) = compute_date(days_since_epoch);
    let weekday: usize = ((days_since_epoch + 4) % 7) as usize;
    let day_name: &[u8; 3] = &DAYS[weekday];
    let month_name: &[u8; 3] = &MONTHS[month as usize - 1];
    if year <= MAX_FOUR_DIGIT_YEAR {
        let mut buf: [u8; 29] = [0u8; 29];
        buf[0..3].copy_from_slice(day_name);
        buf[3] = GMT_COMMA;
        buf[4] = DATE_TIME_SEP;
        write_two_digits(&mut buf, 5, day);
        buf[7] = DATE_TIME_SEP;
        buf[8..11].copy_from_slice(month_name);
        buf[11] = DATE_TIME_SEP;
        write_four_digits(&mut buf, 12, year);
        buf[16] = DATE_TIME_SEP;
        write_two_digits(&mut buf, 17, hours);
        buf[19] = TIME_COLON;
        write_two_digits(&mut buf, 20, minutes);
        buf[22] = TIME_COLON;
        write_two_digits(&mut buf, 23, seconds);
        buf[25..29].copy_from_slice(&GMT_SUFFIX);
        return ascii_bytes_to_string(&buf);
    }
    let day_str: &str = unsafe { from_utf8_unchecked(day_name) };
    let month_str: &str = unsafe { from_utf8_unchecked(month_name) };
    format!("{day_str}, {day:02} {month_str} {year} {hours:02}:{minutes:02}:{seconds:02} GMT")
}

/// Gets the current year.
///
/// # Returns
///
/// - `u64` - The current year
#[inline(always)]
pub fn year() -> u64 {
    compute_date(now_duration().as_secs() / SECONDS_PER_DAY).0
}

/// Gets the current month.
///
/// # Returns
///
/// - `u64` - The current month (1-12)
#[inline(always)]
pub fn month() -> u64 {
    compute_date(now_duration().as_secs() / SECONDS_PER_DAY).1
}

/// Gets the current day.
///
/// # Returns
///
/// - `u64` - The current day of the month
#[inline(always)]
pub fn day() -> u64 {
    compute_date(now_duration().as_secs() / SECONDS_PER_DAY).2
}

/// Gets the current hour.
///
/// # Returns
///
/// - `u64` - The current hour (0-23)
#[inline(always)]
pub fn hour() -> u64 {
    let remaining_seconds: u64 = now_duration().as_secs() % SECONDS_PER_DAY;
    let timezone_offset: u64 = from_env_var().value();
    ((remaining_seconds + timezone_offset) / SECONDS_PER_HOUR) % HOURS_PER_DAY
}

/// Gets the current minute.
///
/// # Returns
///
/// - `u64` - The current minute (0-59)
#[inline(always)]
pub fn minute() -> u64 {
    (now_duration().as_secs() % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE
}

/// Gets the current second.
///
/// # Returns
///
/// - `u64` - The current second (0-59)
#[inline(always)]
pub fn second() -> u64 {
    now_duration().as_secs() % SECONDS_PER_MINUTE
}

/// Gets the current timestamp in milliseconds.
///
/// # Returns
///
/// - `u64` - The current timestamp in milliseconds since Unix epoch
#[inline(always)]
pub fn millis() -> u64 {
    now_duration().subsec_millis() as u64
}

/// Gets the current timestamp in microseconds.
///
/// # Returns
///
/// - `u64` - The current timestamp in microseconds since Unix epoch
#[inline(always)]
pub fn micros() -> u64 {
    now_duration().subsec_micros() as u64
}

/// Calculates the current year, month, day, hour, minute, second, millisecond and microsecond.
///
/// # Returns
///
/// - `(u64, u64, u64, u64, u64, u64, u64, u64)` - Tuple containing:
///   - Year
///   - Month
///   - Day
///   - Hour (0-23)
///   - Minute (0-59)
///   - Second (0-59)
///   - Milliseconds in current second
///   - Microseconds in current second
#[inline(always)]
pub fn calculate_time() -> (u64, u64, u64, u64, u64, u64, u64, u64) {
    let duration: Duration = now_duration();
    let total_seconds: u64 = duration.as_secs();
    let nanoseconds: u64 = duration.subsec_nanos() as u64;
    let milliseconds: u64 = nanoseconds / 1_000_000;
    let microseconds: u64 = nanoseconds / 1_000;
    let (year, month, day): (u64, u64, u64) = compute_date(total_seconds / SECONDS_PER_DAY);
    let remaining_seconds: u64 = total_seconds % SECONDS_PER_DAY;
    let timezone_offset: u64 = from_env_var().value();
    let hour: u64 = ((remaining_seconds + timezone_offset) / SECONDS_PER_HOUR) % HOURS_PER_DAY;
    let minute: u64 = (remaining_seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
    let second: u64 = remaining_seconds % SECONDS_PER_MINUTE;
    (
        year,
        month,
        day,
        hour,
        minute,
        second,
        milliseconds,
        microseconds,
    )
}

/// Gets the current time with milliseconds, including the date and time.
///
/// # Returns
///
/// - `String` - The formatted time as `YYYY-MM-DD HH:MM:SS.sss`
pub fn time_millis() -> String {
    let (year, month, day, hour, minute, second, millisecond, _): (
        u64,
        u64,
        u64,
        u64,
        u64,
        u64,
        u64,
        u64,
    ) = calculate_time();
    if year <= MAX_FOUR_DIGIT_YEAR {
        let mut buf: [u8; 23] = [0u8; 23];
        write_datetime_prefix(&mut buf, year, month, day, hour, minute, second);
        buf[19] = TIME_DOT;
        write_three_digits(&mut buf, 20, millisecond);
        return ascii_bytes_to_string(&buf);
    }
    let mut date_time: String = String::with_capacity(28);
    let _: fmt::Result = write!(
        &mut date_time,
        "{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}.{millisecond:03}"
    );
    date_time
}

/// Gets the current time with microseconds, including the date and time.
///
/// # Returns
///
/// - `String` - The formatted time as `YYYY-MM-DD HH:MM:SS.ssssss`
pub fn time_micros() -> String {
    let (year, month, day, hour, minute, second, _, microseconds): (
        u64,
        u64,
        u64,
        u64,
        u64,
        u64,
        u64,
        u64,
    ) = calculate_time();
    if year <= MAX_FOUR_DIGIT_YEAR {
        let mut buf: [u8; 26] = [0u8; 26];
        write_datetime_prefix(&mut buf, year, month, day, hour, minute, second);
        buf[19] = TIME_DOT;
        write_three_digits(&mut buf, 20, microseconds / 1_000);
        write_three_digits(&mut buf, 23, microseconds % 1_000);
        return ascii_bytes_to_string(&buf);
    }
    let mut date_time: String = String::with_capacity(32);
    let _: fmt::Result = write!(
        &mut date_time,
        "{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}.{microseconds:06}"
    );
    date_time
}

/// Gets the current timestamp in seconds since Unix epoch.
///
/// # Returns
///
/// - `u64` - The current timestamp in seconds
#[inline(always)]
pub fn timestamp() -> u64 {
    let timezone_offset: u64 = from_env_var().value();
    now_duration().as_secs().saturating_add(timezone_offset)
}

/// Gets the current timestamp in milliseconds since Unix epoch.
///
/// # Returns
///
/// - `u64` - The current timestamp in milliseconds
#[inline(always)]
pub fn timestamp_millis() -> u64 {
    let timezone_offset: u64 = from_env_var().value();
    let duration: Duration = now_duration();
    (duration.as_secs().saturating_add(timezone_offset)) * 1000 + duration.subsec_millis() as u64
}

/// Gets the current timestamp in microseconds since Unix epoch.
///
/// # Returns
///
/// - `u64` - The current timestamp in microseconds
#[inline(always)]
pub fn timestamp_micros() -> u64 {
    let timezone_offset: u64 = from_env_var().value();
    let duration: Duration = now_duration();
    (duration.as_secs().saturating_add(timezone_offset)) * 1_000_000
        + duration.subsec_micros() as u64
}