Date Format

Hi

Is there any simple way to convert (and validate) a date from one format to another ?

PHP strtotime have limits before 1970 or bayond 2038 (windows 32bit system) but my mysql seems to work perfectly.

So how to check these cases:

1/2/1940 -> convert to 1940-02-01

31/2/1940 -> (is not valid february has not 31 days)

1/03/2003 -> convert to 2003-03-01

31/2/2060 -> (is not valid february has not 31 days)

06/2/2060 -> convert to 2060-02-06

and vice versa.

I found Datetime PHP class but seems not woks in some cases…

http://www.php.net/manual/en/class.datetime.php

So How to handle it ?

Many thanks

You don’t need a external library to do this php has awesome datatime class introduced in 5.3

http://php.net/datetime.createfromformat

$your_date="1/2/1940";

$formated_date=DateTime::createFromFormat(‘d/m/Y’,$your_date);

if($formated_date){

//if format is correct if will return true

$your_date=$formated_date->format(‘Y-m-d’);

//this will set your new date

}

$your_date="31/2/1940";

$formated_date=DateTime::createFromFormat(‘d/m/Y’,$your_date);

//format is invalid return false

if($formated_date){

$your_date=$formated_date->format(‘Y-m-d’);

}

datetime has some issues. For example

31/02/2013 converted to 02/03/2013 (wrong for me)

If I use


function validateDate($date, $format = 'Y-m-d')

{

    $dt = DateTime::createFromFormat($format, $date);

    return $dt && $dt->format($format) == $date;

}

It works, but when I Use ‘31/2/2013’ (single month without zero) the above function retutn false

$dt->format($format) return ‘31/02/2013’ that is different of ‘31/2/2013’

So could you give me an example ?

Thanks

Hi!

According to my answer

http://www.yiiframework.com/forum/index.php/topic/51895-date-format/page__view__findpost__p__240604

There are some issues with that so, do you fix these issues with your code?

Thanks