[Phpwm] strtotime() date format

David Goodwin david at codepoets.co.uk
Tue Sep 18 14:27:37 BST 2007


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

David Edwards wrote:
> What's an elegant way of getting around the fact that strtotime()
> expects US English dates (mm/dd/yy) instead of dd/mm/yy? Say for
> instance if I wanted to do something easy, like work out the number of
> days between the strings '13/01/07' and '01/02/07'?
> 
> Explode the dates on slashes and feed them in the wrong way round?


Hah! this is my pet php annoyance (of the year, so far).

I submitted a bug on bugs.php.net this morning for, but it doesn't look
like it's been 'accepted' yet into the web interface..


Anyway, we currently use something ugly like the following :

$v = '30/06/2007';
$format = "d/m/Y";
$regexp = '![/\.:\s]!';
$keys = preg_split($regexp, $format);
/* example array('H', 'i', 's', 'Y', 'm', 'd') */
$values = preg_split($regexp, $v);
/* example array('30', '06', '2006'); */

$results=array();
foreach($keys as $key) {
     $value = array_shift($values);
     $results[$key] = $value;
}
/* example array('d' => '30', 'm' => '6', 'Y' => '2006') */

foreach(array('H', 'i', 's', 'm', 'd', 'Y') as $tmp) {
    if(isset($results[$tmp])) {
        $mktime_args[] = $results[$tmp];
    }
    else {
        $mktime_args[] = 0;
    }
}

$date = new DateTime();
$r = $date->setDate($mktime_args[5], $mktime_args[3], $mktime_args[4]);
if ($r === false) {
    throw new XYZException("Boo! Hiss!");
}
$r = $date->setTime($mktime_args[0], $mktime_args[1], $mktime_args[2]);
if ($r === false) {
    throw new XYZException("Boo! Hiss!!");
}


Then you can do :

$date->format("Y/m/d");


We use the DateTime object to handle dates before 1970 or after 2038;
something mktime/strtotime/date aren't happy at doing. I think
internally within DateTime there is a float, instead of an int, which is
what all the others use.

(The exception messages aren't real; but saying PropelException()
wouldn't make much difference!).

thanks
David.
- --
David Goodwin

[ david at codepoets dot co dot uk ]
[ http://www.codepoets.co.uk       ]
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFG79H0/ISo3RF5V6YRApKOAJ0W7jv4qUMeDGhx2Bh+JOdkcVTkUQCgu4vt
6CQIeksNccz+lWUVhbtXQSg=
=b5PO
-----END PGP SIGNATURE-----



More information about the Phpwm mailing list