Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Date Regex

Status
Not open for further replies.

rob51383

Programmer
Jun 23, 2004
134
US
Simple question, but I have always been lost when it comes to regular expression.

I need to convert a date that is given in the format "20050302" to "2005-03-02".

So I need a regex that will count 4 insert a "-" then count 2 and insert another "-".
 
Code:
my $date="20050302";
$date=substr($date,0,4)."-".substr($date,4,2)."-".substr($date,6,2);

Firing up the regex engine for this would be overkill IMO

--Paul

cigless ...
 
TIMTOWDTI:
Code:
substr $date, $_, 0, '-' for ( 6, 4 );

... or ...
Code:
$date = join '-', unpack "A4A2A2", $date;
 
Just for gits and shiggles, I'll go the other route:
Code:
use Date::Parse;
use Time::Format;
$date = $time{'yyyy-mm-dd', str2time($date)};
but if ever there were overkill...

________________________________________
Andrew

I work for a gift card company!
 
Code:
#!perl
# "20050302" to "2005-03-02".
$date = '20050302';
$date =~ s/(\d{4})(\d{2})(\d{2})/$1-$2-$3/;
print "TIMTOWDTI: $date ;-)\n";

'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 
Well, while we're still TIMTOWTDIing and the regexps have entered the fray:
Code:
print join '-', ( $date =~ /(\d{4})(\d{2})(\d{2})/ );

... or ...

Code:
$date =~ s/(?=\d{4}$|\d{2}$)/-/g;
print $date,"\n";

Isn't Perl great ...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top