Perl - How to convert a date?

How to convert the date format YYYY-MM-DDTHH: MM: SSZ to YYYY-MM-DD HH: MM + 8 hours?

For instance:

Input: 2011-07-07T18:05:45Z Output: 2011-07-08 02:05 
+4
source share
5 answers

Let's start with the Rahul snippet and add the date and math output to the format ...

 use DateTime; use DateTime::Format::ISO8601; use DateTime::Format::Strptime; my $string = '2011-07-07T18:05:45Z'; my $dt = DateTime::Format::ISO8601->parse_datetime( $string ); die "Impossible time" unless $dt; my $formatter = new DateTime::Format::Strptime(pattern => '%Y-%m-%d %T'); $dt->add( hours => 8 )->set_formatter($formatter); print "$dt\n"; 

I added the use of DateTime :: Format :: Strptime to specify the desired output format.

Then I added three more lines:

  • First I create a formatter and give it the output template that I want.
  • Then I add eight hours to the original date, and I assign the output of formatter by associating the set_formatter () call with the add () call.
  • Then I print it.
+6
source

Are you using datetime modules?

In particular, here is a link to DateTime :: Format :: ISO8601 , which reads / writes the ISO 8601 format that you mentioned as your input.

+2
source

If you don't have a DateTime, you probably have Time :: Piece:

 use strict; use warnings; use Time::Piece; use Time::Seconds qw(ONE_HOUR); my $str = '2011-07-07T18:05:45Z'; my $t = Time::Piece->strptime($str, "%Y-%m-%dT%TZ"); $t += 8 * ONE_HOUR; print $t->strftime("%Y-%m-%d %H:%M"),"\n"; 
+1
source

This does not work, result 2010-02-28T15: 21: 33

Then do it with difficulty ...

 use Time::Local use warnings; use strict; $time = '2010-02-28T15:21:33Z'; my ($year, month, day) = split (/-/, $time) $year -= 1900; #Year is an offset of 1900 $month -= 1; #Months are 0 - 11 #Now split the time off of the day (DDTHH:MM:SS) $day = substr($day, 0, 2); time = substr($day, 3) #Now split the time (my $hour, $minute, $second) = split(/:/, $time); $second =~ s/Z$//; #Remove Z my $time_converted = timelocal($second, $minute, $hour, $day, $month, $year); #Now you have the time, Add eight hours my $hours_in_seconds = 8 * 60 * 60; $time_converted += $hours_in_seconds; # Almost done: Convert time back into the correct array: ($second, $minute, $hour, $day, $month, $year) = localtime($time_converted); $year += 1900; $month += 1; # Now, reformat: my $formatted_time = sprint (%04d-%02d-%02d %02d:%02d), $year, $month, $day, $hour, $minute; 
0
source

Taken from

How can I check "yyyy-MM-dd'T'HH: mm: ssZ"? UTC date / timestamp with Perl?

 use DateTime; use DateTime::Format::ISO8601; my $string = '2010-02-28T15:21:33Z'; my $dt = DateTime::Format::ISO8601->parse_datetime( $string ); die "Impossible time" unless $dt; 
-1
source

All Articles