W3CDTF は、Dublin Core モジュールの dc:date で使われる日時の形式。
RSS 出力時に dc:date を使いたいので、time 関数の戻り値から W3CDTF な文字列を返す Perl の関数を作った。


#==============================================================================
# format W3CDTF datetime strings
# 
# format:
#
#   to_W3CDTF_string(time, time_difference)
#
# description:
#
#   Returns W3CDTF datetime string.
#   This function's argument is a time as returned by the time function.
#
# synopsis:
#
#  my $w3cdtf = to_W3CDTF_string(time(), '+09:00');
#  print "$w3cdtf\n"; # ex. 2005-05-19T23:45:50+09:00
#
# references:
#
#   * W3C - Date and Time Formats
#     http://www.w3.org/TR/NOTE-datetime
#
#   * localtime - perldoc.perl.org
#     http://perldoc.perl.org/functions/localtime.html
#
#   * sprintf - perldoc.perl.org
#     http://perldoc.perl.org/functions/sprintf.html
#
#==============================================================================
sub to_W3CDTF_string {
  my $time = shift;
  my $td   = shift;
  my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time);
  my $result =
    sprintf(
      "%04d-%02d-%02dT%02d:%02d:%02d%s",
      $year + 1900, $mon + 1, $mday, $hour, $min, $sec, $td);
  return $result;
}

CPAN を探すと DateTime::Format::W3CDTF というモジュールが見つかるが、これ自体が他のモジュールに依存しているし、W3CDTF を出力するだけならオーバースペック。

tags: zlashdot Weblog

Posted by NI-Lab. (@nilab)