View Full Version : 12h format to 24h format in XML

01-02-2012, 06:04 PM
The observation time is in 12h format. How to change it to 24h format?

Working PHP:


$xslDoc = new DOMDocument();

$xmlDoc = new DOMDocument();

$proc = new XSLTProcessor();
echo $proc->transformToXML($xmlDoc);

Working XSL:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<xsl:template match="data">
<xsl:apply-templates select="./current_condition" />

<xsl:template match="current_condition">
<td style="width: 96px">
<p>Observation Time: <xsl:value-of select="./observation_time" /></p>
<p><xsl:value-of select="./temp_C" />C</p>


01-02-2012, 09:03 PM
They should just make a setting to allow users to select 24H or 12H time.
You should email them and ask about it. That would be the easiest.
It would be very easy for them to add that option.

In the meantime, someone will have to give you a function to convert.
I don't have the time right this moment.


01-02-2012, 11:29 PM
There are several ways to do this both XSLT and PHP side. The problem is really your use of XSLProcessor in PHP, which limits the XSLT options to that in the libxslt version.
PHP wise you can use a formatter by running a custom function that takes the time, uses strtotime to convert it, and return it in the new format. This requires the use of the php: namespace in the XSLT though, but is more reliable than assuming that you have 2.0 available to use. One of your other threads (here: http://www.codingforums.com/showpost.php?p=1175655&postcount=4) does just this purpose, but the name of the function may not make a lot of sense since I wrote it for the day of the week. The only thing different is that the format would instead be provided to it as 'h:s' instead of the 'l'.

XSLT can use the format-date function (I think that's what it is, or date-format one of the two). The problem is the processor may not support that in PHP due to its version.
There is a pure XSL solution I found here: http://stackoverflow.com/questions/7921564/convert-24-hour-time-to-12-hour-time-in-xslt. That appears that it should work on a 1.0 version of XSLT as well.

You could also force the dom to add the child node for the XSLT and pump the pure XML out instead. Pro would be that its the browser is now responsible for parsing it, while the con is the browser is responsible for parsing it. IMO, the vast majority of the browsers in use will support XML and XSLT parsing, so this is actually a feasible option to use.

01-04-2012, 02:22 PM
It was more straight forward than could have been imagined.