ctp
ctp

Reputation: 93

custom date format to mysql in php

From a custom utility class, I get the format of a date variable in the following format: d-m-Y. My plan is to use Date('Y-m-d', strtotime($myCustomDate)) but I'm not sure that PHP will return me the right date every time. How can I be sure that my approach is safe?

How can I know that 02-03-2013 will not be transformed as mysql equivalent of 03 February 2013, when I need 02 March 2013.

How do you deal with this problem?

Upvotes: 0

Views: 878

Answers (2)

Robbert
Robbert

Reputation: 6582

If the format is always d-m-Y, then you can use a preg_split function to break the date into its component parts and then reformat it using date

<?PHP 
  $date = "3-13-2013";
  $date_parts = preg_split("/-/",$date);
  $newDate = Date("Y-m-d",mktime(0, 0, 0, $date_parts[0], $date_parts[1], $date_parts[2]));
?>

This will result in $newDate having the value 2013-03-13.

Upvotes: 0

Nick Andriopoulos
Nick Andriopoulos

Reputation: 10643

The safest way (other than using timestamps, which is a whole different story), would be to use the YYYY-MM-DD format, since there can not be the inverse ( ie YYYY-DD-MM is not defined), and MySQL understands it well.

You can then use PHP to convert it to any other desired format.

Upvotes: 1

Related Questions