<?php
/**
 * W3C date parsing code
 * for deanspace.org project
 * 
 * Largely cribbed from PEAR::Date
 *
 * Date spec: http://www.w3.org/TR/NOTE-datetime
 *
 * @version  0.1
 * @author  Paul Bissex <pb@e-scribe.com>
 *
 * @license MIT
 */
 


/**
 * Returns a Unix timestamp for a GMT date
 *
 * @param  $date_string string  Date in ISO 8601 format
 * @return  int  Unix timestamp; -1 on failure
 */
function w3c_to_gmtime($date_string)
    {
    
$pattern "/
        ^(\d{4})-(\d{2})-(\d{2})
        ([T\s]?(\d{2}):(\d{2}):?(\d{2})?\.?(\d{2})?
        (Z|([\+\-]\d{2}):(\d{2}))?)?$
        /xi"
;
                
    
preg_match ($pattern$date_string$matches);
    
    
$year $matches[1];
    
$month $matches[2];
    
$day $matches[3];
    
$hour = (isset($matches[5]) ? $matches[5] : 0);
    
$minute = (isset($matches[6]) ? $matches[6] : 0);
    
$second = (isset($matches[7]) ? $matches[7] : 0);
    
$centisecond = (isset($matches[8]) ? $matches[8] : 0);
    
$tz_hours = (isset($matches[10]) ? $matches[10] : 0);
    
$tz_minutes = (isset($matches[11]) ? $matches[11] : 0);
    
    
/// $tz_hours is signed, so we can just add it
    
$hour += $tz_hours;
    
/// $tz_minutes is unsigned, so we take sign from $tz_hours
    
if (substr($tz_hours01) == "-")
        {
        
$minute -= $tz_minutes;
        }
    else
        {
        
$minute += $tz_minutes;    
        }
    
$time gmmktime ($hour$minute$second$month$day$year);
    return (
$time);
    }
 
/**
 * Test function for w3c_to_gmtime()
 */
function test()
    {
    
$test_times = array (
        
'2001',
        
'2001-02',
        
'2001-02-03',
        
'2001-02-03T05:06',
        
'2001-02-03T05:06:07.08',
        
'2001-02-03T05:06+09:00',
        
'2001-02-03T05:06-09:00',
        
'2001-02-03T05:06Z',
        
'2001-02-03T05:06:07+09:00',
        
'2001-02-03T05:06:07-09:00',
        
'2001-02-03T05:06:07.08+09:00',
        
'2001-02-03T05:06:07.08-00:30',
        
'2001-02-03T05:06:07.08+00:30',
        
'2001-02-03T05:06:07.08-09:00'
        
);
    foreach (
$test_times as $test_time)
        {
        
$result w3c_to_gmtime($test_time);
        print 
"$test_time ==> $result (";
        if (
$result)
            {
            print 
gmdate ('Y-m-d h:i:s'$result);
            }
        else
            {
            print 
"error";
            }
            print 
")\n";
        }
    }
?>
<html>
<h2>testing w3c_to_gmtime()...</h2>
<pre>
<?php
test
();
?>
</pre>
</html>