Skip to content

Instantly share code, notes, and snippets.

@salortiz
Last active May 7, 2016 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salortiz/051c7a81400522e30a7cf12377c02f70 to your computer and use it in GitHub Desktop.
Save salortiz/051c7a81400522e30a7cf12377c02f70 to your computer and use it in GitHub Desktop.
POSIX strftime for Perl6
use v6;
use NativeCall;
constant MAX_BUF_SIZE = 255; # Seems reasonable
constant time_t = size_t; # Best guess.
my class tm is repr('CStruct') { }; # Fields can be added when needed
my sub gmtime(time_t is rw -->tm) is native { * };
my sub strftime(utf8, size_t, Str, tm -->size_t) is native { * };
sub PosixFormat(DateTime:D $time, Str $format) is export {
my time_t $t = $time.posix;
my utf8 $b .= allocate(MAX_BUF_SIZE);
my $res = strftime($b, $b.bytes, $format, my $tm = gmtime($t));
$b.subbuf(0,$res).decode;
}
# Test with:
#$ perl6 -I. -e 'use strftime; DateTime.now.&PosixFormat("%a, %d %b %Y %T GMT").say';
#
# augmenting DateTime is left as an exercise to the reader.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment