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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Date Formatting

Status
Not open for further replies.

squidster

Technical User
Oct 13, 2002
55
GB
I am trying to work out how to convert UK date format (DD/MM/YYY) to a format that will be accepted by MySQL (YYYY-MM-DD), so far I have been almost successful by using the following:-

[tt]
$mysqlDate = "1/1/2005";

//split day, month and year into an array
$date_array = explode("/", $$mysqlDate );

// trim off leading zeros from month and day
$date_array[0] = ltrim($date_array[0],'0');
$date_array[1] = ltrim($date_array[1],'0');

//repad day and month with 0, if applicable
$$mysqlDate = $date_array[2] . &quot;-&quot; . ($date_array[1] < 10 ? &quot;0&quot; : &quot;&quot;) .$date_array[1] . &quot;-&quot; . ($date_array[1] < 10 ? &quot;0&quot; : &quot;&quot;) . $date_array[0];

echo $$mysqlDate ;
[/tt]

Which appears to work, until I try a date of 10/1/2005 or 10/01/2005, which for some reason give output of 2005-01-010.

Can anyone spot what the problem may be please?

Is there a better way to do this?

thanks
 
If it where me I would store it as a Unix timestamp and then using the getdate function in PHP to convert into into any date format you want, for example.

$unixdate = time();

$date = getdate($unixdate);

$current_date = $date('mday') . '/' . $date('mon') . '/' . $date('Year');

for more info on getdate go here:

Hope it helps
 
Thanks anotherDeclan, as luck would have it I just stumbled accross another forum and found this:-

[tt]
//split day, month and year into an array
$date_array = explode(&quot;/&quot;,$mysqlEventDate);

//convert to UNIX timestamp format with mktime() and reformat with date()
$NewFormat = date('Y-m-d',mktime (0,0,0,$date_array['1'], $date_array['0'], $date_array['2']));
[/tt]

which is great as I don't really want to store a timestamp unecessarily
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top