Sunday, May 19, 2013

Perl snippets - Date manipulation

I am an amateur web perl programmer. All my slightly complicated web sites are built using perl. When I get stuck on some small bit of code the answer can sometimes be found on the internet somewhere.

From time to time I am going to post up some of the solutions I have found on my travels in the hope that it may help someone else out.

So the problem:

On one of my website I am automating the creation of a spreadsheet for upload to the google merchant's feed. I needed to create the entry for the Sale price effective date.

This is not something I store in the main database so needed to create the entry on the fly. Basically I needed to create the following entry:

2013-05-19T17:44:51Z/2013-06-19T17:44:51Z

So I started with today's date and then added a month to it, then put in the google specific bits like the '/' and the Z.

Here is the code:

use Time::Piece;

my $t = localtime;
my $t2 = $t->add_months(1);
my $t3 = $t->datetime.'Z/'.$t2->datetime.'Z';

Basically call the module Time::Piece then set variable $t to localtime. Create second variable $t2 which is $t + 1 month and then merge it all together in variable $t3 with $t being put into the correct format "2013-05-19T17:44:51" append a 'Z/' and then amend the other date in a month's time.

Simple really. 

No comments: