views:

118

answers:

3

I'm trying to convert the following XML into a Time:

 <time hour="18" minute="05" timezone="Eastern" utc-hour="-4" utc-minute="00" />

I'm parsing the XML using SimpleXML, and storing that in a class. I also tried printing out the following:

print strtotime($x->time->attributes()->hour . ":" . $x->time->attributes()->minute) . "<br>\n";

The results I got from that print looked something like this:

1249254300

I guess the result I'm expecting would be either 18:05 or 6:05 PM

Is there any way I can get it to convert to the style I'm expecting? Also, if I were to add the timezone onto the end is there any way for it to figure that out?

+4  A: 

I would advise against using strtotime here. Instead try mktime.

$time=mktime($x->time->attributes()->hour,$x->time->attributes()->minute,0,0,0,0)

Also you need to format the time stamp (what you printed out was the unix representation). You can do this with the date function.

date("H:i", $time);
C. Ross
+1  A: 

You can bring it into a form strtotime() understands (including the timezone info)

<?php
$x = new SimpleXMLElement('<x>
    <time hour="18" minute="05" timezone="Eastern" utc-hour="-4" utc-minute="00" />
</x>');

$ts = sprintf('%02d:%02d %+03d%02d', $x->time['hour'], $x->time['minute'], $x->time['utc-hour'], $x->time['utc-minute']);
$ts = strtotime($ts);
echo gmdate(DateTime::RFC1123, $ts), "\n", date(DateTime::RFC1123, $ts);

My local timezone is CET/CEST (utc+2 in this case), therefore the script prints

Mon, 03 Aug 2009 22:05:00 +0000
Tue, 04 Aug 2009 00:05:00 +0200
VolkerK
+1  A: 

The strToTime function will recognize a date or time in string format, and then convert it to a Unix Timestamp (the number of seconds since the Unix Epoch (the Unix epoch being January 1, 1970 a midnight, UTC).

So, what you need to do is take the resul of your strToTime function, and use the date function to format them in a more human readable way

//24 hour clock
print date(
      'H:i',
      strtotime($x->time->attributes()->hour . ":" . $x->time->attributes()->minute) . "<br>\n");

//12 hour clock
print date(
      'h:i a',
      strtotime($x->time->attributes()->hour . ":" . $x->time->attributes()->minute) . "<br>\n");

Full formatting options can be found the date entry on php.net

Alan Storm