tags:

views:

157

answers:

5

Hi

How convert a date from dd-mm-yy to mm-dd-yy

below is my code

<?
$date= date('d-m-y');
echo date('m-d-Y',strtotime($date));
?>

but the result is : 09-10-2001

i need 09-01-2010

+3  A: 

This won't work:

date('m-d-y', strtotime($the_original_date));

If you have PHP 5.3, you can do:

$date = DateTime::createFromFormat('d-m-y', '09-10-01');
$new_date = $date->format('m-d-Y');

Otherwise:

$parts = explode('-', $original_date);
$new_date = $parts[1] . '-' . $parts[0] . '-' . $parts[2];
jasonbar
This will fail in certain situations because strtotime recognizes US English dates. 03-01-10 will be interpreted as March 1, 2010 not January 3, 2010.
stillstanding
this is my code <?$date= date('d-m-y');echo date('m-d-Y',strtotime($date));but the result is: 09-10-2001i need 09-01-2010thanks for your reply
Testadmin
Updated answer because it was entirely wrong. Thanks @stillstanding.
jasonbar
+1 for using the DateTime function
Stann0rz
A: 

try this date("m-d-y", {your date variable})

pymendoza
+2  A: 

You can do:

$input = 'dd-mm-yy';
$a = explode('-',$input);
$result = $a[1].'-'.$a[0].'-'.$a[2];                                      
codaddict
$old_date = date($date); $old_date_timestamp = strtotime($old_date); $new_date = date('d-m-Y', $old_date_timestamp);
JapanPro
A: 

If the format is always like above, this should work:

$pieces = explode("-", $yourTimestring);
$timestamp = mktime(0,0,0,$pieces[1], $pieces[0], $pieces[2]);
$newDateStr = date("m-d-y", $timestamp);

Edit: True, just saw the answer from "codaddict" and yeah, if i alredy split it up you could also concatenate it directly ^^

TheCandyMan666
A: 

You could use the sscanf function if you dont have PHP 5.3 available and make use of the argument swapping option:

$theDate = '01-02-03';
print join(sscanf($theDate, '%2$2s-%1$2s-%3$2s'), '-');
# output: 02-01-03

sscanf basically parses the provided string in an array based on the provided format, swapping the first matched argument (the day) with the second (the month), leaving the third one (year) untouched and then this array is joined again with the - as separator.

Max