Timestamps using ISO8601 strings

03 Mar 2010

You want to generate timestamps, be able to store them, retrieve them and do math with them; but you don’t really care about parsing (i.e. you’re not reading user input, just manipulating timestamps that you created yourself).

Use perl’s DateTime module, and the functions bellow to serialize and deserialize.

use DateTime;

sub now {
  return DateTime->now(time_zone => 'UTC');
}

sub date_str {
  return $_[0]->iso8601() . "Z";
}

sub str_date {
  die unless $_[0] =~ m/^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)Z$/;
  return DateTime->new(year => $1, month => $2, day => $3,
    hour => $4, minute => $5, second => $6, time_zone  => 'UTC');
}