diff --git a/vlib/time/time.c.v b/vlib/time/time.c.v index 9816706dfd..75ebf2aa18 100644 --- a/vlib/time/time.c.v +++ b/vlib/time/time.c.v @@ -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])) } +} diff --git a/vlib/time/time_test.v b/vlib/time/time_test.v index c657b2c8ce..dc9e1b1516 100644 --- a/vlib/time/time_test.v +++ b/vlib/time/time_test.v @@ -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') +}