time: implement Time.strftime(fmt string) as a wrapper for strftime(3) (#13898)

pull/13911/head
Cameron Katri 2022-04-02 11:33:37 -04:00 committed by GitHub
parent 42f92db0ab
commit d585fbea8a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 0 deletions

View File

@ -12,9 +12,14 @@ pub struct C.timeval {
}
fn C.localtime(t &C.time_t) &C.tm
fn C.localtime_r(t &C.time_t, tm &C.tm)
fn C.time(t &C.time_t) C.time_t
fn C.gmtime(t &C.time_t) &C.tm
fn C.gmtime_r(t &C.time_t, res &C.tm) &C.tm
fn C.strftime(buf &C.char, maxsize C.size_t, fmt &C.char, tm &C.tm) C.size_t
// now returns current local time.
pub fn now() Time {
$if macos {
@ -123,3 +128,17 @@ fn convert_ctime(t C.tm, microsecond int) Time {
is_local: true
}
}
// strftime returns the formatted time using `strftime(3)`
pub fn (t Time) strftime(fmt string) string {
mut tm := &C.tm{}
$if windows {
tm = C.gmtime(voidptr(&t.unix))
} $else {
C.gmtime_r(voidptr(&t.unix), tm)
}
mut buf := [1024]C.char{}
fmt_c := unsafe { &C.char(fmt.str) }
C.strftime(&buf[0], C.size_t(sizeof(buf)), fmt_c, tm)
return unsafe { cstring_to_vstring(&char(&buf[0])) }
}

View File

@ -263,3 +263,7 @@ fn test_recursive_local_call() {
assert now_tm.str() == now_tm.local().str()
assert now_tm.local().str() == now_tm.local().local().str()
}
fn test_strftime() {
assert '1980 July 11' == time_to_test.strftime('%Y %B %d')
}