View Single Post
Old 05-29-2008, 02:55 PM   #18 (permalink)
sketchMedia
The Prestige
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
sketchMedia is on a distinguished road
Default

Combined into Wildhoney's class (which i have slightly modified, i added 'array_key_exists, instead of 'in_array' and a few small things)

PHP Code:
class DateDiff
{
    private 
$m_pDates;
    private 
$m_aConversions;
 
    public function 
__construct($iStartDate$iEndDate$szTimeZone '')
    {
        
$this->m_aConversions = array
        (
            
'Seconds' => 0,
            
'Minutes' => 60,
            
'Hours' => 3600,
            
'Days' => 86400,
            
'Weeks' => 604800
        
);
        
$pDateTimezone = new DateTimeZone(
            (!empty(
$szTimeZone)) ?
                
$szTimeZone :
                
date_default_timezone_get()
        );
        
//get time and add related offsets(if any)

        
$this->m_pDates->start strtotime($iStartDate) + $pDateTimezone->getOffset(new DateTime($iStartDate));
        
$this->m_pDates->end strtotime($iEndDate) + $pDateTimezone->getOffset(new DateTime($iEndDate));
    }
  
    public function 
__call($szCall$aArgs)
    {
        if(!
preg_match('~^in(.+)~'$szCall$aMatches))
        {
            throw new 
Exception('Invalid conversion format supplied.');
        }
  
        
$szCall $aMatches[1];
        if (!
array_key_exists($szCall$this->m_aConversions))
        {
            throw new 
Exception('Specified conversion is not available.');
        }
      
        if(
$this->m_aConversions[$szCall] == 0)
        {
            return 
$this->m_pDates->end $this->m_pDates->start;
        }
      
        return (
$this->m_pDates->end $this->m_pDates->start) / $this->m_aConversions[$szCall];
    }

Now we can:

PHP Code:
date_default_timezone_set('Asia/Tokyo');

$pDate = new DateDiff('2008-01-29''2008-01-30');
    
printf('Difference: %d seconds<br />'$pDate->inSeconds());
printf('Difference: %d minutes<br />'$pDate->inMinutes());
printf('Difference: %d hours<br />'$pDate->inHours());
printf('Difference: %d days<br />'$pDate->inDays());
printf('Difference: %d weeks<br />'$pDate->inWeeks()); 
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)

Last edited by sketchMedia : 05-30-2008 at 08:27 AM. Reason: made code smaller
sketchMedia is offline  
Reply With Quote