Reputation: 203
I pull a date from a file and I'm creating a datetime object by using this command and then adding 1 to it to get the next date.
my $parseit = DateTime::Format::Strptime->new(pattern => '%Y%m%d');
my $lastdate = "20190115";
my $tempdate = $parseit->parse_datetime($lastdate);
my $date_up1 = $tempdate->add(days => 1);
but in printing out the variable $date_up1 I always get it in the form %Y-%m-%d. How can I just get it returned in the pattern that I selected.
Upvotes: 2
Views: 137
Reputation: 385647
While DateTime::Format::Strptime can be used to both parse and format date times, it doesn't set itself as the default formatter for the DateTime objects it creates as you expect. You can do that explicitly by adding the following:
$tempdate->set_formatter($parseit);
After cleaning up your code, it looks like this:
my $date = "20190115";
my $format = DateTime::Format::Strptime->new(
pattern => '%Y%m%d',
on_error => 'croak',
);
my $dt = $format->parse_datetime($date);
$dt->set_formatter($format);
$dt->add( days => 1 );
say $dt;
Alternatively, all of the following work without setting the formatter:
$format->format_datetime($dt)
$dt->strftime("%Y%m%d")
(Most flexible, but introduces duplicate code in this case)$dt->ymd("")
(Simplest in this case)Upvotes: 1
Reputation: 9231
strptime and thus DateTime::Format::Strptime by default only dictates how you parse the input into a DateTime object. DateTime objects default to a specific stringification, which you are seeing. In order to stringify it in a certain way, you can use its strftime method.
print $date_up1->strftime('%Y%m%d');
Upvotes: 2