How to parse a string into a DateTime object in Perl?

前端 未结 4 1524
旧时难觅i
旧时难觅i 2020-12-03 02:23

I know about the DateTime Perl module, and many of the DateTime::Format:: modules to parse specific kinds of date/time formats. However given some examples of d

相关标签:
4条回答
  • 2020-12-03 03:11

    I tend to use Time::Piece simply because it's part of the standard Perl module set since version 5.10.

    You can't beat it's ability to parse date strings.

    my $time = Time::Piece->strptime(
          "October 28, 2011 9:00 PM PDT",
          "%B %d, %Y %r %Z");
    
    0 讨论(0)
  • 2020-12-03 03:18

    Have a look at the Date::Parse module, i.e. the str2time() function. It has support for most of the commonly used formats.

    Example:

    use Date::Parse;
    use DateTime;
    
    my $str = "Tue, 20 Sep 2011 08:51:08 -0500";
    my $epoch = str2time($str);
    my $datetime = DateTime->from_epoch(epoch => $epoch);
    
    0 讨论(0)
  • 2020-12-03 03:21

    DateTime::Format::Strptime takes date/time strings and parses them into DateTime objects.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use DateTime::Format::Strptime;
    
    my $parser = DateTime::Format::Strptime->new(
      pattern => '%B %d, %Y %I:%M %p %Z',
      on_error => 'croak',
    );
    
    my $dt = $parser->parse_datetime('October 28, 2011 9:00 PM PDT');
    
    print "$dt\n";
    

    The character sequences used in the pattern are POSIX standard. See 'man strftime' for details.

    0 讨论(0)
  • 2020-12-03 03:21

    If you are looking for common date/time formats have a look at DateTime::Locale

    use DateTime::Locale
    my $locale = DateTime::Locale->load('DE_de');
    

    The following methods return strings appropriate for the DateTime->format_cldr() method:

    $locale->date_format_full()
    $locale->date_format_long()
    $locale->date_format_medium()
    $locale->date_format_short()
    $locale->date_format_default()
    $locale->time_format_full()
    $locale->time_format_long()
    $locale->time_format_medium()
    $locale->time_format_short()
    $locale->time_format_default()
    $locale->datetime_format_full()
    $locale->datetime_format_long()
    $locale->datetime_format_medium()
    $locale->datetime_format_short()
    $locale->datetime_format_default()
    

    You can parse Dates with the DateTime::Format::CLDR module

    use DateTime::Format::CLDR;
    # 1. Basic example
    my $cldr = DateTime::Format::CLDR->new(
        pattern     => 'dd.MM.yyyy HH:mm:ss',
        locale      => 'de_DE',
        time_zone   => 'Europe/Berlin',
    );
    my $dt = $cldr->parse_datetime('26.06.2013 11:05:28');
    
    0 讨论(0)
提交回复
热议问题