note 101990 modified in datetime.diff by danbrown

From: Date: Tue, 01 Feb 2011 17:40:30 +0000
Subject: note 101990 modified in datetime.diff by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176570@lists.php.net to get a copy of this message
I found that DateTime::diff isn't as accurate as I thought. I calculated the age gap between now and a birthdate from before 1970 (unix epoch). Here's what I got: Given today is January 21st, 2011: <?php date_default_timezone_set('Europe/Berlin'); // birthdate format is YYYY-MM-DD $birth = new DateTime('1966-01-21'); $today = new DateTime(); $diff = $birth->diff($today); echo $diff->format('%y'); // will output 45 $birth = new DateTime('1966-01-23'); $today = new DateTime(); $diff = $birth->diff($today); echo $diff->format('%y'); // will output 45 wrongly $birth = new DateTime('1966-01-24'); // three days difference! $today = new DateTime(); $diff = $birth->diff($today); echo $diff->format('%y'); // will output 44 - correct ?> When calculating with the date() function it was more accurate (didn't use seconds/hours for comparison). Note that 3 days may be a lot if you want to create invoices and have to check against a given age to determine if the customer is chargable for taxes and so on. If someone also found this behaviour I'd like to hear about it - give me a quick mail at schindhelm (at) gmail (dot) com. Thanks. --was-- I found that DateTime::diff isn't as accurate as I thought. I calculated the age gap between now and a birthdate from before 1970 (unix epoch). Here's what I got: Given today is January 21st, 2011: <?php date_default_timezone_set('Europe/Berlin'); // birthdate format is YYYY-MM-DD $birth = new DateTime('1966-01-21'); $today = new DateTime(); $diff = $birth->diff($today); echo $diff->format('%y'); // will output 45 wrongly $birth = new DateTime('1966-01-23'); $today = new DateTime(); $diff = $birth->diff($today); echo $diff->format('%y'); // will output 45 wrongly $birth = new DateTime('1966-01-24'); // three days difference! $today = new DateTime(); $diff = $birth->diff($today); echo $diff->format('%y'); // will output 44 - correct ?> When calculating with the date() function it was more accurate (didn't use seconds/hours for comparison). Note that 3 days may be a lot if you want to create invoices and have to check against a given age to determine if the customer is chargable for taxes and so on. If someone also found this behaviour I'd like to hear about it - give me a quick mail at schindhelm (at) gmail (dot) com. Thanks. http://php.net/manual/en/datetime.diff.php

« previous php.notes (#176570) next »