I use xlstproc to transform some xml file to another xml format file, during transformation, I need to calculate the time difference value (durations in seconds or minutes:seconds) between start and end fields.
...
<start>2011-12-13 16:15:26</start>
<end>2011-12-13 16:17:27</end>
...
I found a Template Syntax, but failed to make use of it.
<xsl:call-template name="date:duration">
<xsl:with-param name="seconds" select="number" />?
</xsl:call-template>
Would appreciate somebody can give me a hint how to achieve my goal. Thanks in advance!
I did some of your work for you and found this date:duration function, which you seem to be trying to use. However, date:duration converts a number of seconds into a duration formatted string, whereas you want to find the difference (duration) between two datetime strings.
You probably want date:difference instead. If you read the documentation for this function/template, you'll find this about the arguments:
There are italics there in the original: CCYY-MM-DDThh:mm:ss except the T is not italicized. In other words, the time strings need a literal
T
between the date and the time, whereas yours have a space.So I would suggest fixing that:
Pass the
start
andend
strings as parameters to the template. You can do this by just passing thestart
andend
element nodes, which will be automatically converted to strings based on their text content:This code assumes that the context node is the parent of the
<start>
and<end>
elements. After the above code, the variable$time-diff-sec
will contain a result tree fragment, which can be converted to a number usingnumber($time-diff-sec)
if necessary.Let us know whether that works. If not, state specifically what the result was and how it differs from what you expected.
Update:
I just noticed that you are using xsltproc (which uses libxslt). According to this documentation, libxslt supports
date:difference
(anddate:seconds
) natively. So you can call these functions as functions instead of defining a named template and calling it as a template. That would be a lot less code for you, albeit less portable:As before, you will need to declare the
date
namespace prefix somewhere, usually on yourxsl:stylesheet
element:Update 2:
See this answer for a portable XSLT 1.0 template to convert a date string to number of seconds, which allows you to easily subtract one date from another. (Thanks to Sam B for that comment).