xquery或xslt将时间小时转换为PT*H*M格式



我是XQuery和XSLT的新手。

我正在寻找一个XQuery或XQuery函数来将时间总计(即5小时转换为PT5H或5.5小时转换为PT5H30M(

不确定XQuery是否能做到这一点。如果没有,任何XSLT1.0函数也可以。

您不能用分数小时或分钟来定义xs:dayTimeDuration,但可以使用分数秒,因此只需将小时乘以3600并创建以秒为单位的持续时间:

xs:dayTimeDuration(
concat(
'PT', 
$hours * 3600,
'S'
)
)

例如

let 
$hours:= 5.551245
return
xs:dayTimeDuration(
concat(
'PT', 
$hours * 3600,
'S'
)
)

返回:PT5H33M4.482S

考虑以下示例:

XML

<input>
<hours>5</hours>
<hours>5.5</hours>
<hours>5.555</hours>
</input>

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/input">
<output>
<xsl:for-each select="hours">
<xsl:variable name="seconds" select=". * 3600" />
<xsl:variable name="h" select="floor($seconds div 3600)"/>
<xsl:variable name="m" select="floor($seconds div 60) mod 60"/>
<xsl:variable name="s" select="$seconds mod 60"/>
<duration>
<xsl:text>PT</xsl:text>
<xsl:value-of select="$h"/>
<xsl:text>H</xsl:text>
<xsl:value-of select="$m"/>
<xsl:text>M</xsl:text>
<xsl:value-of select="$s"/>
<xsl:text>S</xsl:text>
</duration>
</xsl:for-each>
</output>
</xsl:template>
</xsl:stylesheet>

结果

<?xml version="1.0" encoding="UTF-8"?>
<output>
<duration>PT5H0M0S</duration>
<duration>PT5H30M0S</duration>
<duration>PT5H33M18S</duration>
</output>

这假设输入值不能为负数。


请注意,PT5H30MPT330M是相同持续时间的有效表达式,因此您可以将输入值乘以60(假设您只需要精确到一分钟(。

最新更新