Skip to content

Instantly share code, notes, and snippets.

@samebchase
Created April 2, 2020 15:48
Show Gist options
  • Save samebchase/f4a587c34263909dea6b719e59eacf39 to your computer and use it in GitHub Desktop.
Save samebchase/f4a587c34263909dea6b719e59eacf39 to your computer and use it in GitHub Desktop.
Utility to convert milliseconds since the UNIX Epoch to a readable timestamp. Also, handles timezone offsets.
#!/usr/bin/env raku
use v6;
grammar Offset {
token TOP { <sign> <hours> ':' <minutes> }
token sign { '+' | '-' }
token hours { <number> }
token minutes { <number> }
token number { \d+ }
}
sub offset-to-seconds($offset-string) {
# String is in the format "+5:30", "-8:45" etc.
my $match = Offset.parse($offset-string);
#say $match; # DEBUG
$match // die 'Invalid offset format. Use something like "+5:30" or "-8:45" instead.';
my $seconds = $match<hours> × 3600 + $match<minutes> × 60;
$match<sign> eq '-' ?? -$seconds !! $seconds;
}
sub ms-to-secs ($ms) {
round($ms.parse-base(10) ÷ 1000, 1);
}
multi sub MAIN($milliseconds) {
my $seconds = ms-to-secs($milliseconds);
say DateTime.new($seconds);
}
multi sub MAIN($milliseconds, $offset) {
my $offset-secs = offset-to-seconds($offset);
my $seconds = ms-to-secs($milliseconds);
say DateTime.new($seconds).in-timezone($offset-secs);
}
~
❯ timestamp-from-ms 1585725108000
2020-04-01T07:11:48Z
~
❯ timestamp-from-ms 1585725108000 +5:30
2020-04-01T12:41:48+05:30
~
❯ timestamp-from-ms 1585725108000 -5:30
2020-04-01T01:41:48-05:30
~
❯ timestamp-from-ms 1585725108000 ffff
Invalid offset format. Use something like "+5:30" or "-8:45" instead.
in sub offset-to-seconds at /Users/samuel/bin/timestamp-from-ms line 19
in sub MAIN at /Users/samuel/bin/timestamp-from-ms line 39
in block <unit> at /Users/samuel/bin/timestamp-from-ms line 5
~
❯ timestamp-from-ms
Usage:
timestamp-from-ms <milliseconds>
timestamp-from-ms <milliseconds> <offset>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment