time-format 1.2.2

A lightweight library for formatting Unix timestamps with millisecond precision in UTC and local time
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
#![doc = include_str!("../README.md")]

use std::{
    convert::TryInto,
    ffi::CString,
    fmt,
    mem::MaybeUninit,
    os::raw::{c_char, c_int},
};

#[cfg(not(target_env = "msvc"))]
use std::os::raw::c_long;

#[allow(non_camel_case_types)]
type time_t = i64;

/// A UNIX timestamp in seconds.
pub type TimeStamp = i64;

/// A UNIX timestamp with millisecond precision.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct TimeStampMs {
    /// Seconds since the UNIX epoch.
    pub seconds: i64,
    /// Milliseconds component (0-999).
    pub milliseconds: u16,
}

impl TimeStampMs {
    /// Create a new TimeStampMs from seconds and milliseconds.
    pub fn new(seconds: i64, milliseconds: u16) -> Self {
        let milliseconds = milliseconds % 1000;
        Self {
            seconds,
            milliseconds,
        }
    }

    /// Convert from a TimeStamp (seconds only).
    pub fn from_timestamp(ts: TimeStamp) -> Self {
        Self {
            seconds: ts,
            milliseconds: 0,
        }
    }

    /// Get the total milliseconds since the UNIX epoch.
    pub fn total_milliseconds(&self) -> i64 {
        self.seconds * 1000 + self.milliseconds as i64
    }
}

// Unix/Linux/macOS tm struct with timezone fields
#[cfg(not(target_env = "msvc"))]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
struct tm {
    pub tm_sec: c_int,
    pub tm_min: c_int,
    pub tm_hour: c_int,
    pub tm_mday: c_int,
    pub tm_mon: c_int,
    pub tm_year: c_int,
    pub tm_wday: c_int,
    pub tm_yday: c_int,
    pub tm_isdst: c_int,
    pub tm_gmtoff: c_long,
    pub tm_zone: *mut c_char,
}

// Windows MSVC tm struct without timezone fields
#[cfg(target_env = "msvc")]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
struct tm {
    pub tm_sec: c_int,
    pub tm_min: c_int,
    pub tm_hour: c_int,
    pub tm_mday: c_int,
    pub tm_mon: c_int,
    pub tm_year: c_int,
    pub tm_wday: c_int,
    pub tm_yday: c_int,
    pub tm_isdst: c_int,
}

// Unix/Linux/macOS - use _r variants
#[cfg(not(target_env = "msvc"))]
extern "C" {
    fn gmtime_r(ts: *const time_t, tm: *mut tm) -> *mut tm;
    fn localtime_r(ts: *const time_t, tm: *mut tm) -> *mut tm;
    fn strftime(s: *mut c_char, maxsize: usize, format: *const c_char, timeptr: *const tm)
        -> usize;
}

// Windows MSVC - use _s variants with explicit 64-bit time (note: reversed parameter order)
#[cfg(target_env = "msvc")]
extern "C" {
    fn _gmtime64_s(tm: *mut tm, ts: *const time_t) -> c_int;
    fn _localtime64_s(tm: *mut tm, ts: *const time_t) -> c_int;
    fn strftime(s: *mut c_char, maxsize: usize, format: *const c_char, timeptr: *const tm)
        -> usize;
}

// Platform-specific wrappers for gmtime
#[cfg(not(target_env = "msvc"))]
unsafe fn safe_gmtime(ts: *const time_t, tm: *mut tm) -> bool {
    !gmtime_r(ts, tm).is_null()
}

#[cfg(target_env = "msvc")]
unsafe fn safe_gmtime(ts: *const time_t, tm: *mut tm) -> bool {
    _gmtime64_s(tm, ts) == 0
}

// Platform-specific wrappers for localtime
#[cfg(not(target_env = "msvc"))]
unsafe fn safe_localtime(ts: *const time_t, tm: *mut tm) -> bool {
    !localtime_r(ts, tm).is_null()
}

#[cfg(target_env = "msvc")]
unsafe fn safe_localtime(ts: *const time_t, tm: *mut tm) -> bool {
    _localtime64_s(tm, ts) == 0
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Error {
    /// Error occurred while parsing or converting time
    TimeError,
    /// Error occurred with timestamp value (e.g., timestamp out of range)
    InvalidTimestamp,
    /// Error occurred while formatting time
    FormatError,
    /// Error with format string (e.g., invalid format specifier)
    InvalidFormatString,
    /// Error with UTF-8 conversion from C string
    Utf8Error,
    /// Error with null bytes in input strings
    NullByteError,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::TimeError => write!(f, "Time processing error"),
            Error::InvalidTimestamp => write!(f, "Invalid timestamp value"),
            Error::FormatError => write!(f, "Time formatting error"),
            Error::InvalidFormatString => write!(f, "Invalid format string"),
            Error::Utf8Error => write!(f, "UTF-8 conversion error"),
            Error::NullByteError => write!(f, "String contains null bytes"),
        }
    }
}

impl std::error::Error for Error {}

/// Validates a strftime format string for correct syntax.
/// This performs a basic validation to catch common errors.
///
/// Returns Ok(()) if the format appears valid, or an error describing the issue.
pub fn validate_format(format: impl AsRef<str>) -> Result<(), Error> {
    let format = format.as_ref();

    // Check for empty format
    if format.is_empty() {
        return Err(Error::InvalidFormatString);
    }

    // Check for null bytes (which would cause CString creation to fail)
    if format.contains('\0') {
        return Err(Error::NullByteError);
    }

    let mut chars = format.chars().peekable();
    while let Some(c) = chars.next() {
        // Look for % sequences
        if c == '%' {
            match chars.next() {
                // These are the most common format specifiers
                Some('a') | Some('A') | Some('b') | Some('B') | Some('c') | Some('C')
                | Some('d') | Some('D') | Some('e') | Some('F') | Some('g') | Some('G')
                | Some('h') | Some('H') | Some('I') | Some('j') | Some('k') | Some('l')
                | Some('m') | Some('M') | Some('n') | Some('p') | Some('P') | Some('r')
                | Some('R') | Some('s') | Some('S') | Some('t') | Some('T') | Some('u')
                | Some('U') | Some('V') | Some('w') | Some('W') | Some('x') | Some('X')
                | Some('y') | Some('Y') | Some('z') | Some('Z') | Some('%') | Some('E')
                | Some('O') | Some('+') => {
                    // Valid format specifier
                    continue;
                }
                Some(_c) => {
                    // Unknown format specifier
                    return Err(Error::InvalidFormatString);
                }
                None => {
                    // % at end of string
                    return Err(Error::InvalidFormatString);
                }
            }
        }
    }

    // Check for the special {ms} sequence format
    let ms_braces = format.match_indices('{').count();
    let ms_closing_braces = format.match_indices('}').count();
    if ms_braces != ms_closing_braces {
        return Err(Error::InvalidFormatString);
    }

    Ok(())
}

/// Time components.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Components {
    /// Second.
    pub sec: u8,
    /// Minute.
    pub min: u8,
    /// Hour.
    pub hour: u8,
    /// Day of month.
    pub month_day: u8,
    /// Month - January is 1, December is 12.
    pub month: u8,
    /// Year.
    pub year: i16,
    /// Day of week.
    pub week_day: u8,
    /// Day of year.    
    pub year_day: u16,
}

/// Split a timestamp into its components in UTC timezone.
pub fn components_utc(ts_seconds: TimeStamp) -> Result<Components, Error> {
    let mut tm = MaybeUninit::<tm>::uninit();
    if !unsafe { safe_gmtime(&ts_seconds, tm.as_mut_ptr()) } {
        return Err(Error::TimeError);
    }
    let tm = unsafe { tm.assume_init() };
    Ok(Components {
        sec: tm.tm_sec as _,
        min: tm.tm_min as _,
        hour: tm.tm_hour as _,
        month_day: tm.tm_mday as _,
        month: (1 + tm.tm_mon) as _,
        year: (1900 + tm.tm_year) as _,
        week_day: tm.tm_wday as _,
        year_day: tm.tm_yday as _,
    })
}

/// Split a timestamp into its components in the local timezone.
pub fn components_local(ts_seconds: TimeStamp) -> Result<Components, Error> {
    let mut tm = MaybeUninit::<tm>::uninit();
    if !unsafe { safe_localtime(&ts_seconds, tm.as_mut_ptr()) } {
        return Err(Error::TimeError);
    }
    let tm = unsafe { tm.assume_init() };
    Ok(Components {
        sec: tm.tm_sec as _,
        min: tm.tm_min as _,
        hour: tm.tm_hour as _,
        month_day: tm.tm_mday as _,
        month: (1 + tm.tm_mon) as _,
        year: (1900 + tm.tm_year) as _,
        week_day: tm.tm_wday as _,
        year_day: tm.tm_yday as _,
    })
}

/// Convert a `std::time::SystemTime` to a UNIX timestamp in seconds.
///
/// This function converts a `std::time::SystemTime` instance to a `TimeStamp` (Unix timestamp in seconds).
/// It handles the conversion and error cases related to negative timestamps or other time conversion issues.
///
/// # Examples
///
/// ```rust
/// use std::time::{SystemTime, UNIX_EPOCH, Duration};
///
/// // Convert the current system time to a timestamp
/// let system_time = SystemTime::now();
/// let timestamp = time_format::from_system_time(system_time).unwrap();
///
/// // Convert a specific time
/// let past_time = UNIX_EPOCH + Duration::from_secs(1500000000);
/// let past_timestamp = time_format::from_system_time(past_time).unwrap();
/// assert_eq!(past_timestamp, 1500000000);
/// ```
///
/// ## Working with Time Components
///
/// You can use the function to convert a `SystemTime` to components:
///
/// ```rust
/// use std::time::{SystemTime, UNIX_EPOCH, Duration};
///
/// // Create a specific time: January 15, 2023 at 14:30:45 UTC
/// let specific_time = UNIX_EPOCH + Duration::from_secs(1673793045);
///
/// // Convert to timestamp
/// let ts = time_format::from_system_time(specific_time).unwrap();
///
/// // Get the time components
/// let components = time_format::components_utc(ts).unwrap();
///
/// // Verify the time components
/// assert_eq!(components.year, 2023);
/// assert_eq!(components.month, 1); // January
/// assert_eq!(components.month_day, 15);
/// assert_eq!(components.hour, 14);
/// assert_eq!(components.min, 30);
/// assert_eq!(components.sec, 45);
/// ```
///
/// ## Formatting with strftime
///
/// Convert a `SystemTime` and format it as a string:
///
/// ```rust
/// use std::time::{SystemTime, UNIX_EPOCH, Duration};
///
/// // Create a specific time
/// let specific_time = UNIX_EPOCH + Duration::from_secs(1673793045);
///
/// // Convert to timestamp
/// let ts = time_format::from_system_time(specific_time).unwrap();
///
/// // Format as ISO 8601
/// let iso8601 = time_format::format_iso8601_utc(ts).unwrap();
/// assert_eq!(iso8601, "2023-01-15T14:30:45Z");
///
/// // Custom formatting
/// let custom_format = time_format::strftime_utc("%B %d, %Y at %H:%M:%S", ts).unwrap();
/// assert_eq!(custom_format, "January 15, 2023 at 14:30:45");
/// ```
pub fn from_system_time(time: std::time::SystemTime) -> Result<TimeStamp, Error> {
    time.duration_since(std::time::UNIX_EPOCH)
        .map_err(|_| Error::TimeError)?
        .as_secs()
        .try_into()
        .map_err(|_| Error::InvalidTimestamp)
}

/// Return the current UNIX timestamp in seconds.
pub fn now() -> Result<TimeStamp, Error> {
    from_system_time(std::time::SystemTime::now())
}

/// Convert a `std::time::SystemTime` to a UNIX timestamp with millisecond precision.
///
/// This function converts a `std::time::SystemTime` instance to a `TimeStampMs` (Unix timestamp with millisecond precision).
/// It extracts both the seconds and milliseconds components from the system time.
///
/// # Examples
///
/// ```rust
/// use std::time::{SystemTime, UNIX_EPOCH, Duration};
///
/// // Convert the current system time to a timestamp with millisecond precision
/// let system_time = SystemTime::now();
/// let timestamp_ms = time_format::from_system_time_ms(system_time).unwrap();
/// println!("Seconds: {}, Milliseconds: {}", timestamp_ms.seconds, timestamp_ms.milliseconds);
///
/// // Convert a specific time with millisecond precision
/// let specific_time = UNIX_EPOCH + Duration::from_millis(1500000123);
/// let specific_ts_ms = time_format::from_system_time_ms(specific_time).unwrap();
/// assert_eq!(specific_ts_ms.seconds, 1500000);
/// assert_eq!(specific_ts_ms.milliseconds, 123);
/// ```
///
/// ## Using with TimeStampMs methods
///
/// ```rust
/// use std::time::{SystemTime, UNIX_EPOCH, Duration};
///
/// // Create a precise time: 1500000 seconds and 123 milliseconds after the epoch
/// let specific_time = UNIX_EPOCH + Duration::from_millis(1500000123);
///
/// // Convert to TimeStampMs
/// let ts_ms = time_format::from_system_time_ms(specific_time).unwrap();
///
/// // Get total milliseconds
/// let total_ms = ts_ms.total_milliseconds();
/// assert_eq!(total_ms, 1500000123);
/// ```
///
/// ## Formatting timestamps with millisecond precision
///
/// You can format a timestamp with millisecond precision:
///
/// ```rust
/// use std::time::{SystemTime, UNIX_EPOCH, Duration};
///
/// // Create a specific timestamp with millisecond precision
/// // We'll use a fixed timestamp rather than a date calculation to avoid test failures
/// let ts_ms = time_format::TimeStampMs::new(1743087045, 678);
///
/// // Format with milliseconds using your preferred pattern
/// let formatted = time_format::strftime_ms_utc("%Y-%m-%d %H:%M:%S.{ms}", ts_ms).unwrap();
///
/// // Verify the milliseconds are included
/// assert!(formatted.contains(".678"));
///
/// // Format as ISO 8601 with milliseconds
/// let iso8601_ms = time_format::format_iso8601_ms_utc(ts_ms).unwrap();
/// assert!(iso8601_ms.ends_with(".678Z"));
///
/// // Use with common date formats
/// let rfc3339 = time_format::format_common_ms_utc(ts_ms, time_format::DateFormat::RFC3339).unwrap();
/// assert!(rfc3339.contains(".678"));
/// ```
///
/// ## Converting between TimeStamp and TimeStampMs
///
/// ```rust
/// use std::time::{SystemTime, UNIX_EPOCH, Duration};
///
/// // Create a system time with millisecond precision
/// let system_time = UNIX_EPOCH + Duration::from_millis(1673793045678);
///
/// // Convert to TimeStampMs
/// let ts_ms = time_format::from_system_time_ms(system_time).unwrap();
/// assert_eq!(ts_ms.seconds, 1673793045);
/// assert_eq!(ts_ms.milliseconds, 678);
///
/// // Convert to TimeStamp (loses millisecond precision)
/// let ts = time_format::from_system_time(system_time).unwrap();
/// assert_eq!(ts, 1673793045);
///
/// // Convert from TimeStamp to TimeStampMs
/// let ts_ms_from_ts = time_format::TimeStampMs::from_timestamp(ts);
/// assert_eq!(ts_ms_from_ts.seconds, ts);
/// assert_eq!(ts_ms_from_ts.milliseconds, 0); // milliseconds are lost
/// ```
pub fn from_system_time_ms(time: std::time::SystemTime) -> Result<TimeStampMs, Error> {
    let duration = time
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|_| Error::TimeError)?;

    let seconds = duration
        .as_secs()
        .try_into()
        .map_err(|_| Error::InvalidTimestamp)?;
    let millis = duration.subsec_millis() as u16;

    Ok(TimeStampMs::new(seconds, millis))
}

/// Return the current UNIX timestamp with millisecond precision.
pub fn now_ms() -> Result<TimeStampMs, Error> {
    from_system_time_ms(std::time::SystemTime::now())
}

/// Return the current time in the specified format, in the UTC time zone.
/// The time is assumed to be the number of seconds since the Epoch.
///
/// This function will validate the format string before attempting to format the time.
pub fn strftime_utc(format: impl AsRef<str>, ts_seconds: TimeStamp) -> Result<String, Error> {
    let format = format.as_ref();

    // Validate the format string
    validate_format(format)?;

    let mut tm = MaybeUninit::<tm>::uninit();
    if !unsafe { safe_gmtime(&ts_seconds, tm.as_mut_ptr()) } {
        return Err(Error::TimeError);
    }
    let tm = unsafe { tm.assume_init() };

    format_time_with_tm(format, &tm)
}

/// Return the current time in the specified format, in the local time zone.
/// The time is assumed to be the number of seconds since the Epoch.
///
/// This function will validate the format string before attempting to format the time.
pub fn strftime_local(format: impl AsRef<str>, ts_seconds: TimeStamp) -> Result<String, Error> {
    let format = format.as_ref();

    // Validate the format string
    validate_format(format)?;

    let mut tm = MaybeUninit::<tm>::uninit();
    if !unsafe { safe_localtime(&ts_seconds, tm.as_mut_ptr()) } {
        return Err(Error::TimeError);
    }
    let tm = unsafe { tm.assume_init() };

    format_time_with_tm(format, &tm)
}

// Internal helper function to format time with a tm struct
fn format_time_with_tm(format: &str, tm: &tm) -> Result<String, Error> {
    let format_len = format.len();
    let format = CString::new(format).map_err(|_| Error::NullByteError)?;
    let mut buf_size = format_len;
    let mut buf: Vec<u8> = vec![0; buf_size];

    // Initial attempt
    let mut len = unsafe {
        strftime(
            buf.as_mut_ptr() as *mut c_char,
            buf_size,
            format.as_ptr() as *const c_char,
            tm,
        )
    };

    // If the format is invalid, strftime returns 0 but won't use more buffer space
    // We try once with a much larger buffer to distinguish between these cases
    if len == 0 {
        // Try with a larger buffer first
        buf_size *= 10;
        buf.resize(buf_size, 0);

        len = unsafe {
            strftime(
                buf.as_mut_ptr() as *mut c_char,
                buf_size,
                format.as_ptr() as *const c_char,
                tm,
            )
        };

        // If still 0 with a much larger buffer, it's likely an invalid format
        if len == 0 {
            return Err(Error::InvalidFormatString);
        }
    }

    // Keep growing the buffer if needed
    while len == 0 {
        buf_size *= 2;
        buf.resize(buf_size, 0);
        len = unsafe {
            strftime(
                buf.as_mut_ptr() as *mut c_char,
                buf_size,
                format.as_ptr() as *const c_char,
                tm,
            )
        };
    }

    buf.truncate(len);
    String::from_utf8(buf).map_err(|_| Error::Utf8Error)
}

/// Return the current time in the specified format, in the UTC time zone,
/// with support for custom millisecond formatting.
///
/// The standard format directives from strftime are supported.
/// Additionally, the special text sequence '{ms}' will be replaced with the millisecond component.
///
/// Example: strftime_ms_utc("%Y-%m-%d %H:%M:%S.{ms}", ts_ms)
///
/// This function will validate the format string before attempting to format the time.
pub fn strftime_ms_utc(format: impl AsRef<str>, ts_ms: TimeStampMs) -> Result<String, Error> {
    let format_str = format.as_ref();

    // Validate the format string (validation also checks for balanced braces)
    validate_format(format_str)?;

    // First, format the seconds part
    // Skip validation in strftime_utc since we already did it
    let mut tm = MaybeUninit::<tm>::uninit();
    if !unsafe { safe_gmtime(&ts_ms.seconds, tm.as_mut_ptr()) } {
        return Err(Error::TimeError);
    }
    let tm = unsafe { tm.assume_init() };

    let seconds_formatted = format_time_with_tm(format_str, &tm)?;

    // If the format contains the {ms} placeholder, replace it with the milliseconds
    if format_str.contains("{ms}") {
        // Format milliseconds with leading zeros
        let ms_str = format!("{:03}", ts_ms.milliseconds);
        Ok(seconds_formatted.replace("{ms}", &ms_str))
    } else {
        Ok(seconds_formatted)
    }
}

/// Return the current time in the specified format, in the local time zone,
/// with support for custom millisecond formatting.
///
/// The standard format directives from strftime are supported.
/// Additionally, the special text sequence '{ms}' will be replaced with the millisecond component.
///
/// Example: strftime_ms_local("%Y-%m-%d %H:%M:%S.{ms}", ts_ms)
///
/// This function will validate the format string before attempting to format the time.
pub fn strftime_ms_local(format: impl AsRef<str>, ts_ms: TimeStampMs) -> Result<String, Error> {
    let format_str = format.as_ref();

    // Validate the format string (validation also checks for balanced braces)
    validate_format(format_str)?;

    // First, format the seconds part
    // Skip validation in strftime_local since we already did it
    let mut tm = MaybeUninit::<tm>::uninit();
    if !unsafe { safe_localtime(&ts_ms.seconds, tm.as_mut_ptr()) } {
        return Err(Error::TimeError);
    }
    let tm = unsafe { tm.assume_init() };

    let seconds_formatted = format_time_with_tm(format_str, &tm)?;

    // If the format contains the {ms} placeholder, replace it with the milliseconds
    if format_str.contains("{ms}") {
        // Format milliseconds with leading zeros
        let ms_str = format!("{:03}", ts_ms.milliseconds);
        Ok(seconds_formatted.replace("{ms}", &ms_str))
    } else {
        Ok(seconds_formatted)
    }
}

/// Format a timestamp according to ISO 8601 format in UTC.
///
/// ISO 8601 is an international standard for date and time representations.
/// This function returns the timestamp in the format: `YYYY-MM-DDThh:mm:ssZ`
///
/// Example: "2025-05-20T14:30:45Z"
///
/// For more details on ISO 8601, see: https://en.wikipedia.org/wiki/ISO_8601
pub fn format_iso8601_utc(ts: TimeStamp) -> Result<String, Error> {
    strftime_utc("%Y-%m-%dT%H:%M:%SZ", ts)
}

/// Format a timestamp with millisecond precision according to ISO 8601 format in UTC.
///
/// ISO 8601 is an international standard for date and time representations.
/// This function returns the timestamp in the format: `YYYY-MM-DDThh:mm:ss.sssZ`
///
/// Example: "2025-05-20T14:30:45.123Z"
///
/// For more details on ISO 8601, see: https://en.wikipedia.org/wiki/ISO_8601
pub fn format_iso8601_ms_utc(ts_ms: TimeStampMs) -> Result<String, Error> {
    strftime_ms_utc("%Y-%m-%dT%H:%M:%S.{ms}Z", ts_ms)
}

/// Format a timestamp according to ISO 8601 format in the local timezone.
///
/// This function returns the timestamp in the format: `YYYY-MM-DDThh:mm:ss±hh:mm`
/// where the `±hh:mm` part represents the timezone offset from UTC.
///
/// Example: "2025-05-20T09:30:45-05:00"
///
/// For more details on ISO 8601, see: https://en.wikipedia.org/wiki/ISO_8601
pub fn format_iso8601_local(ts: TimeStamp) -> Result<String, Error> {
    strftime_local("%Y-%m-%dT%H:%M:%S%z", ts).map(|s| {
        // Standard ISO 8601 requires a colon in timezone offset (e.g., -05:00 not -0500)
        // But strftime just gives us -0500, so we need to insert the colon
        if s.len() > 5 && (s.ends_with('0') || s.chars().last().unwrap().is_ascii_digit()) {
            let len = s.len();
            format!("{}:{}", &s[..len - 2], &s[len - 2..])
        } else {
            s
        }
    })
}

/// Format a timestamp with millisecond precision according to ISO 8601 format in the local timezone.
///
/// This function returns the timestamp in the format: `YYYY-MM-DDThh:mm:ss.sss±hh:mm`
/// where the `±hh:mm` part represents the timezone offset from UTC.
///
/// Example: "2025-05-20T09:30:45.123-05:00"
///
/// For more details on ISO 8601, see: https://en.wikipedia.org/wiki/ISO_8601
pub fn format_iso8601_ms_local(ts_ms: TimeStampMs) -> Result<String, Error> {
    strftime_ms_local("%Y-%m-%dT%H:%M:%S.{ms}%z", ts_ms).map(|s| {
        // Insert colon in timezone offset for ISO 8601 compliance
        let len = s.len();
        if len > 5 && (s.ends_with('0') || s.chars().last().unwrap().is_ascii_digit()) {
            format!("{}:{}", &s[..len - 2], &s[len - 2..])
        } else {
            s
        }
    })
}

/// Format types for common date strings
///
/// This enum provides common date and time format patterns.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum DateFormat {
    /// RFC 3339 (similar to ISO 8601) format: "2025-05-20T14:30:45Z" or "2025-05-20T14:30:45-05:00"
    RFC3339,
    /// RFC 2822 format: "Tue, 20 May 2025 14:30:45 -0500"
    RFC2822,
    /// HTTP format (RFC 7231): "Tue, 20 May 2025 14:30:45 GMT"
    HTTP,
    /// SQL format: "2025-05-20 14:30:45"
    SQL,
    /// US date format: "05/20/2025 02:30:45 PM"
    US,
    /// European date format: "20/05/2025 14:30:45"
    European,
    /// Short date: "05/20/25"
    ShortDate,
    /// Long date: "Tuesday, May 20, 2025"
    LongDate,
    /// Short time: "14:30"
    ShortTime,
    /// Long time: "14:30:45"
    LongTime,
    /// Date and time: "2025-05-20 14:30:45"
    DateTime,
    /// Custom format string
    Custom(&'static str),
}

impl DateFormat {
    /// Get the format string for this format
    fn get_format_string(&self) -> &'static str {
        match self {
            Self::RFC3339 => "%Y-%m-%dT%H:%M:%S%z",
            Self::RFC2822 => "%a, %d %b %Y %H:%M:%S %z",
            Self::HTTP => "%a, %d %b %Y %H:%M:%S GMT",
            Self::SQL => "%Y-%m-%d %H:%M:%S",
            Self::US => "%m/%d/%Y %I:%M:%S %p",
            Self::European => "%d/%m/%Y %H:%M:%S",
            Self::ShortDate => "%m/%d/%y",
            Self::LongDate => "%A, %B %d, %Y",
            Self::ShortTime => "%H:%M",
            Self::LongTime => "%H:%M:%S",
            Self::DateTime => "%Y-%m-%d %H:%M:%S",
            Self::Custom(fmt) => fmt,
        }
    }
}

/// Format a timestamp using a common date format in UTC timezone
///
/// Examples:
/// ```rust
/// let ts = time_format::now().unwrap();
///
/// // Format as RFC 3339
/// let rfc3339 = time_format::format_common_utc(ts, time_format::DateFormat::RFC3339).unwrap();
///
/// // Format as HTTP date
/// let http_date = time_format::format_common_utc(ts, time_format::DateFormat::HTTP).unwrap();
///
/// // Format with a custom format
/// let custom = time_format::format_common_utc(ts, time_format::DateFormat::Custom("%Y-%m-%d")).unwrap();
/// ```
pub fn format_common_utc(ts: TimeStamp, format: DateFormat) -> Result<String, Error> {
    let format_str = format.get_format_string();

    match format {
        DateFormat::RFC3339 => {
            // Handle RFC3339 specially to ensure proper timezone formatting
            strftime_utc(format_str, ts).map(|s| {
                if s.ends_with('0') || s.chars().last().unwrap().is_ascii_digit() {
                    let len = s.len();
                    format!("{}:{}", &s[..len - 2], &s[len - 2..])
                } else {
                    s
                }
            })
        }
        _ => strftime_utc(format_str, ts),
    }
}

/// Format a timestamp using a common date format in local timezone
///
/// Examples:
/// ```rust
/// let ts = time_format::now().unwrap();
///
/// // Format as RFC 2822
/// let rfc2822 = time_format::format_common_local(ts, time_format::DateFormat::RFC2822).unwrap();
///
/// // Format as US date
/// let us_date = time_format::format_common_local(ts, time_format::DateFormat::US).unwrap();
/// ```
pub fn format_common_local(ts: TimeStamp, format: DateFormat) -> Result<String, Error> {
    let format_str = format.get_format_string();

    match format {
        DateFormat::RFC3339 => {
            // Handle RFC3339 specially to ensure proper timezone formatting
            strftime_local(format_str, ts).map(|s| {
                if s.ends_with('0') || s.chars().last().unwrap().is_ascii_digit() {
                    let len = s.len();
                    format!("{}:{}", &s[..len - 2], &s[len - 2..])
                } else {
                    s
                }
            })
        }
        DateFormat::HTTP => {
            // HTTP dates are always in GMT/UTC, so redirect to the UTC version
            format_common_utc(ts, format)
        }
        _ => strftime_local(format_str, ts),
    }
}

/// Format a timestamp with millisecond precision using a common date format in UTC timezone
///
/// This function extends common date formats to include milliseconds where appropriate.
/// For formats that don't typically include milliseconds (like ShortDate), the milliseconds are ignored.
///
/// Examples:
/// ```rust
/// let ts_ms = time_format::now_ms().unwrap();
///
/// // Format as RFC 3339 with milliseconds
/// let rfc3339 = time_format::format_common_ms_utc(ts_ms, time_format::DateFormat::RFC3339).unwrap();
/// // Example: "2025-05-20T14:30:45.123Z"
/// ```
pub fn format_common_ms_utc(ts_ms: TimeStampMs, format: DateFormat) -> Result<String, Error> {
    // For formats that can reasonably include milliseconds, add them
    let format_str = match format {
        DateFormat::RFC3339 => "%Y-%m-%dT%H:%M:%S.{ms}%z",
        DateFormat::SQL => "%Y-%m-%d %H:%M:%S.{ms}",
        DateFormat::DateTime => "%Y-%m-%d %H:%M:%S.{ms}",
        DateFormat::LongTime => "%H:%M:%S.{ms}",
        DateFormat::Custom(fmt) => fmt,
        _ => format.get_format_string(), // Use standard format for others
    };

    match format {
        DateFormat::RFC3339 => {
            // Handle RFC3339 specially for timezone formatting
            strftime_ms_utc(format_str, ts_ms).map(|s| {
                if s.ends_with('0') || s.chars().last().unwrap().is_ascii_digit() {
                    let len = s.len();
                    format!("{}:{}", &s[..len - 2], &s[len - 2..])
                } else {
                    s
                }
            })
        }
        _ => strftime_ms_utc(format_str, ts_ms),
    }
}

/// Format a timestamp with millisecond precision using a common date format in local timezone
///
/// This function extends common date formats to include milliseconds where appropriate.
/// For formats that don't typically include milliseconds (like ShortDate), the milliseconds are ignored.
///
/// Examples:
/// ```rust
/// let ts_ms = time_format::now_ms().unwrap();
///
/// // Format as RFC 3339 with milliseconds in local time
/// let local_time = time_format::format_common_ms_local(ts_ms, time_format::DateFormat::RFC3339).unwrap();
/// // Example: "2025-05-20T09:30:45.123-05:00"
/// ```
pub fn format_common_ms_local(ts_ms: TimeStampMs, format: DateFormat) -> Result<String, Error> {
    // For formats that can reasonably include milliseconds, add them
    let format_str = match format {
        DateFormat::RFC3339 => "%Y-%m-%dT%H:%M:%S.{ms}%z",
        DateFormat::SQL => "%Y-%m-%d %H:%M:%S.{ms}",
        DateFormat::DateTime => "%Y-%m-%d %H:%M:%S.{ms}",
        DateFormat::LongTime => "%H:%M:%S.{ms}",
        DateFormat::Custom(fmt) => fmt,
        _ => format.get_format_string(), // Use standard format for others
    };

    match format {
        DateFormat::RFC3339 => {
            // Handle RFC3339 specially for timezone formatting
            strftime_ms_local(format_str, ts_ms).map(|s| {
                if s.ends_with('0') || s.chars().last().unwrap().is_ascii_digit() {
                    let len = s.len();
                    format!("{}:{}", &s[..len - 2], &s[len - 2..])
                } else {
                    s
                }
            })
        }
        DateFormat::HTTP => {
            // HTTP dates are always in GMT/UTC, so redirect to the UTC version
            format_common_ms_utc(ts_ms, format)
        }
        _ => strftime_ms_local(format_str, ts_ms),
    }
}

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

    #[test]
    fn test_components_utc() {
        // Test a known timestamp: 2023-01-15 14:30:45 UTC
        let ts = 1673793045;
        let components = components_utc(ts).unwrap();

        assert_eq!(components.year, 2023);
        assert_eq!(components.month, 1);
        assert_eq!(components.month_day, 15);
        assert_eq!(components.hour, 14);
        assert_eq!(components.min, 30);
        assert_eq!(components.sec, 45);
    }

    #[test]
    fn test_strftime_utc() {
        // Test a known timestamp: 2023-01-15 14:30:45 UTC
        let ts = 1673793045;
        let formatted = strftime_utc("%Y-%m-%d %H:%M:%S", ts).unwrap();
        assert_eq!(formatted, "2023-01-15 14:30:45");
    }

    #[test]
    fn test_iso8601_utc() {
        let ts = 1673793045;
        let formatted = format_iso8601_utc(ts).unwrap();
        assert_eq!(formatted, "2023-01-15T14:30:45Z");
    }

    #[test]
    fn test_timestamp_ms() {
        let ts_ms = TimeStampMs::new(1673793045, 678);
        assert_eq!(ts_ms.seconds, 1673793045);
        assert_eq!(ts_ms.milliseconds, 678);
        assert_eq!(ts_ms.total_milliseconds(), 1673793045678);
    }

    #[test]
    fn test_strftime_ms_utc() {
        let ts_ms = TimeStampMs::new(1673793045, 678);
        let formatted = strftime_ms_utc("%Y-%m-%d %H:%M:%S.{ms}", ts_ms).unwrap();
        assert_eq!(formatted, "2023-01-15 14:30:45.678");
    }

    #[test]
    fn test_iso8601_ms_utc() {
        let ts_ms = TimeStampMs::new(1673793045, 678);
        let formatted = format_iso8601_ms_utc(ts_ms).unwrap();
        assert_eq!(formatted, "2023-01-15T14:30:45.678Z");
    }

    #[test]
    fn test_validate_format() {
        assert!(validate_format("%Y-%m-%d").is_ok());
        assert!(validate_format("%Y-%m-%d %H:%M:%S").is_ok());
        assert!(validate_format("").is_err());
        assert!(validate_format("%").is_err());
        assert!(validate_format("%Q").is_err()); // Invalid specifier
        assert!(validate_format("test\0test").is_err()); // Null byte
    }

    #[test]
    fn test_common_formats() {
        let ts = 1673793045;

        // Test various common formats
        let sql = format_common_utc(ts, DateFormat::SQL).unwrap();
        assert_eq!(sql, "2023-01-15 14:30:45");

        let datetime = format_common_utc(ts, DateFormat::DateTime).unwrap();
        assert_eq!(datetime, "2023-01-15 14:30:45");

        let short_time = format_common_utc(ts, DateFormat::ShortTime).unwrap();
        assert_eq!(short_time, "14:30");

        let long_time = format_common_utc(ts, DateFormat::LongTime).unwrap();
        assert_eq!(long_time, "14:30:45");
    }

    #[test]
    fn test_from_system_time() {
        use std::time::{Duration, UNIX_EPOCH};

        let system_time = UNIX_EPOCH + Duration::from_secs(1673793045);
        let ts = from_system_time(system_time).unwrap();
        assert_eq!(ts, 1673793045);

        let components = components_utc(ts).unwrap();
        assert_eq!(components.year, 2023);
        assert_eq!(components.month, 1);
        assert_eq!(components.month_day, 15);
    }

    #[test]
    fn test_from_system_time_ms() {
        use std::time::{Duration, UNIX_EPOCH};

        let system_time = UNIX_EPOCH + Duration::from_millis(1673793045678);
        let ts_ms = from_system_time_ms(system_time).unwrap();
        assert_eq!(ts_ms.seconds, 1673793045);
        assert_eq!(ts_ms.milliseconds, 678);
    }

    #[test]
    fn test_epoch() {
        // Test Unix epoch (January 1, 1970, 00:00:00 UTC)
        let components = components_utc(0).unwrap();
        assert_eq!(components.year, 1970);
        assert_eq!(components.month, 1);
        assert_eq!(components.month_day, 1);
        assert_eq!(components.hour, 0);
        assert_eq!(components.min, 0);
        assert_eq!(components.sec, 0);
    }

    #[test]
    fn test_y2k() {
        // Test Y2K (January 1, 2000, 00:00:00 UTC)
        let ts = 946684800;
        let components = components_utc(ts).unwrap();
        assert_eq!(components.year, 2000);
        assert_eq!(components.month, 1);
        assert_eq!(components.month_day, 1);
    }

    #[test]
    fn test_leap_year() {
        // Test February 29, 2020 (leap year)
        let ts = 1582934400;
        let components = components_utc(ts).unwrap();
        assert_eq!(components.year, 2020);
        assert_eq!(components.month, 2);
        assert_eq!(components.month_day, 29);
    }
}