Trying to use DateTime. What's wrong?

前端 未结 2 1300
甜味超标
甜味超标 2021-01-14 23:39

I am trying to get DateTime to out todays date in %d/%m-%Y\' format, but I get undef.

What am I doing wrong?

#         


        
相关标签:
2条回答
  • 2021-01-15 00:14

    It could be written as simple as:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use DateTime ();
    
    my $now = DateTime->now( 'time_zone' => 'UTC' );
    print $now->strftime('%d/%m-%Y');
    
    0 讨论(0)
  • 2021-01-15 00:35

    Generally DateTime formatters will both parse a string to and format a string from a DateTime object. ->parse_datetime will give you a DateTime object from a string, and ->format_datetime will give you a string from a DateTime object. When you have a formatter you want to use to both deserialize and reserialize your dates, you can use it in a few different ways:

    use strict;
    use warnings;
    use Data::Dumper;
    
    use DateTime;
    use DateTime::Format::Strptime;
    
    use 5.012;
    
    my $now = DateTime->now(time_zone => 'local');
    say $now; ### '2011-07-01T08:22:03' - converted to string with default formatter
    
    my $p = DateTime::Format::Strptime->new(
        pattern     => '%d/%m-%Y',
        time_zone   => 'UTC',
        );
    say $p->format_datetime($now); ### use the parser against a DateTime
                                   ### '01/07-2011'
    
    $now->set_formatter($p); ### Set the parser as the default string 
                             ### formatter for the DateTime object
    say $now; ### '01/07-2011' -- from formatter
    
    ### Or set it at object construction
    my $now2 = DateTime->now( time_zone => 'local',
                              formatter => $p,
                            );
    say $now2; ### '01/07-2011' - from formatter
    
    0 讨论(0)
提交回复
热议问题