Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - How to convert a date?

Tags:

date

format

perl

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

For example:

Input: 2011-07-07T18:05:45Z

Output: 2011-07-08 02:05
like image 747
abra Avatar asked Feb 23 '23 16:02

abra


2 Answers

Let's start with Rahul's snippet, and add in the date math and output formatting...

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've added the use of DateTime::Format::Strptime, in order to specify the desired output format.

Then I've added three more lines:

  1. First I create a formatter, and feed it the output pattern I desire.
  2. Next I add eight hours to the original date, and I assign the output formatter by chaining the set_formatter() call to the add() call.
  3. Then I print it.
like image 94
Len Jaffe Avatar answered Feb 26 '23 04:02

Len Jaffe


Are you using the DateTime modules?

Specifically, here's a link to DateTime::Format::ISO8601 that reads/writes ISO 8601 format you mentioned as your input.

like image 35
mrk Avatar answered Feb 26 '23 04:02

mrk