Perl: Using the Date::Calc Module to Generate Date-Related Strings
I have found the Date::Calc module to be quite handy on several occasions. It has many, many methods to do just about anything you can think of with dates. If you haven’t used it before, I would suggest you check it out and give it a try.
Today I’m going to show how I recently had to come up with a string that represented the first 3 characters of the current month in all lowercase plus the current 4-digit year. So if this is February of 2014, the string needed to be “feb2014.” The Date::Calc module came in quite handy for this task.
First I start out by including the module in my script:
use Date::Calc qw(:all);
I will get today’s date with the Today() method:
($today_year, $today_month, $today_day) = Today();
Next we will get the actual name of the month (e.g., February). The second parameter here is the language:
$full_mon = Month_to_Text($today_month, 1); #1 = English
We’ll lowercase the month name:
$short_mon = lc($full_proc_mon);
And then we use a regular expression to discard everything after the first 3 characters:
$short_mon=~s/^(.{3}).*$/$1/g;
Now we combine the month and year to get our string (e.g., “feb2014”):
$month_year = $short_mon . $today_year;
Some of these steps could have been combined, of course, but I have broken it out here for ease of reading and debugging.
Have you used the Date::Calc module for any interesting applications? Share your thoughts in the comments.