Question

I have a text file which I'm converting to a csv file with information that I want to import into a MySQL database.

I currently have the date in this format:

Mar 24

I would like to change that format

YYYY-MM-DD

I would like to do this in perl as I have done all the other bit in the csv file in perl.

Was it helpful?

Solution

This is a tentative solution to your problem using Time::Piece, which is a core module and shouldn't need installing.

I'm very unhappy about your input date format not containing a year. The code below assumes the current year, but I can imagine that a date like Jan 3 should be upgraded to the following year if the code is run on 31 December.

The year has to be included in the string to be parsed because Time::Piece will alter Feb 29 to Mar 1 for non-leap years.

use strict;
use warnings;

use Time::Piece;

print bd_to_ymd('Mar 24');

sub bd_to_ymd {
  my ($bd) = @_;
  my $year = localtime->year;
  my $tp = Time::Piece->strptime("$year $bd", '%Y %b %d');
  $tp->strftime('%Y-%m-%d');
}

output

2014-03-24
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top