Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl - formatting DateTime output

Tags:

datetime

perl

How do I convert my return using DateTime from:

This is my date:2011-11-26T20:11:06 to This is my date:20111126

Using this existing code:

use DateTime qw();
my $dt3 = DateTime->now->subtract(days => 1);
print "This is my date:$dt3\n"
like image 338
jdamae Avatar asked Nov 27 '11 20:11

jdamae


2 Answers

ymd is the simplest:

print "This is my date: ", $dt3->ymd(''), "\n";

strftime is more general purpose:

print "This is my date: ", $dt3->strftime('%Y%m%d'), "\n";

There are also specific (e.g. DateTime::Format::Atom) and general (e.g. DateTime::Format::Strptime) formatting helper tools you can use:

use DateTime::Format::Strptime qw( );
my $format = DateTime::Format::Strptime->new( pattern => '%Y%m%d' );
print "This is my date: ", $format->format_datetime($dt3), "\n";

PS — Your code will give the date in or near England, not the date where you are located. For that, you want

my $dt3 = DateTime->now(time_zone => 'local');

or the more appropriate

my $dt3 = DateTime->today(time_zone => 'local');
like image 172
ikegami Avatar answered Oct 05 '22 01:10

ikegami


Just add ->ymd("") on the second line. The parameter "" is the separator, which you chose to be an empty string.

use DateTime qw();
my $dt3 = DateTime->now->subtract(days => 1)->ymd("");
print "This is my date:$dt3\n"
like image 30
Igor Avatar answered Oct 05 '22 00:10

Igor