Reputation: 3981
Given a date string in the format m-d-Y (e.g, "12-09-2011") how can I display it in the format "m/d/Y" WITHOUT resorting to regular expressions.
Just in case you missed it: without using regular expressions.
I would prefer to use DateTime::createFromFormat()
for this problem, but the server I am using currently doesn't have 5.3.0 on it.
I'd also prefer using date('m/d/Y', strtotime("12-09-2011"))
but strtotime()
doesn't recognize that format properly. It confuses the day and month.
Upvotes: 0
Views: 188
Reputation: 75619
sscanf("12-09-2011", "%d-%d-%d", $month, $day, $year);
echo "$month/$day/$year";
Upvotes: 1
Reputation: 79
What about exploding it? i.e.
$date = explode('-', "12-09-2011");
echo $date[1] . '/' . $date[0] . '/' . $date[2];
Upvotes: 1
Reputation: 360762
No need for heavy artillery. Since you're not rearranging the date components, a simple string search/replace will do:
$string = '12-09-2011';
$fixed = str_replace('-', '/', $string);
If you WERE rearrangine things, e.g. durning your m-d-Y into d/m/y, then you'd need something a bit heavier:
$string = '12-09-2011';
$parts = explode('-', $string); // array(0 => '12', 1 => '09', 2 => '2011');
$fixed = $parts[1] . '/' . $parts[0] . '/' . $parts[2]; // 09/12/2011
Upvotes: 3