tags:

views:

60

answers:

5

So I know how to format a date in PHP, but not from a custom format. I have a date that is a string "YYMMDD" and I want to make it "MMDDYYYY'. strtotime doesn't seem like it would do a good job of this when the MM and DD are both low digits. What is the best way to do this?

+3  A: 

Use str_split:

$date1 = "YYMMDD";
list($yy, $mm, $dd) = str_split($date1, 2);

// MMDDYYYY format, assuming they are all > 2000
$date2 = $mm . $dd . "20" . $yy;
cdmckay
they are not all 2000 and I do need a 4-digit year
@user239292: It's pretty easy to modify that with a simple conditional to differentiate between the 20th and 21st century...
animuson
+2  A: 

If you're running PHP >= 5.3, have a look at DateTime::createFromFormat. Otherwise, if you don't want to use pure string manipulation techniques, use the more primitive strptime together with mktime to parse the time into a UNIX timestamp, which you can then format using date.

deceze
A: 

Ended up doing:

$expiration_date_year   = substr($matches['expiration_date'],0,2);
            $expiration_date_month  = substr($matches['expiration_date'],2,2);
            $expiration_date_day    = substr($matches['expiration_date'],4,2);
            $expiration_date = date('m/d/Y', mktime(0,0,0,$expiration_date_month, $expiration_date_day, $expiration_date_year));
A: 

Have many dates prior to 1910? If not, you could check your YY for <=10, and if true, prepend "20" else prepend "19"... Kinda similar approach to MM and DD check for <10 and prepend a "0" if true... (This is all after exploding, or substring... Assign each part to its own variable, i.e. $M=$MM; $D=$DD; $Y=$YYYY; then concatenate/arrange in whatever order you want... Just another potential way to skin the proverbial cat...

mck66productions
+1  A: 
Anthony Levensalor