我正在使用仅在中央时区(CT)输出服务器时间的系统。我需要在XSLT中将其转换为美国东部时间。XSLT时区转换
有没有内置的方法来翻译这个或我需要使用正则表达式?
<node time="02:14 pm CT" />
电流输出:下午2点14 CT
所需的输出:下午3时14分ET
我正在使用仅在中央时区(CT)输出服务器时间的系统。我需要在XSLT中将其转换为美国东部时间。XSLT时区转换
有没有内置的方法来翻译这个或我需要使用正则表达式?
<node time="02:14 pm CT" />
电流输出:下午2点14 CT
所需的输出:下午3时14分ET
至少有两条主要路径可供选择,将其转换为时间并使用基于时间的库,或将其作为字符串并进行直接字符串操作。以下是字符串处理:
<xsl:variable name="time" select="'11:14 pm CT'"/> <!-- the input value -->
<xsl:variable name="hours" select="number(substring-before($time,':'))"/> <!-- numeric hours -->
<xsl:variable name="mer" select="substring($time,7,2)"/> <!-- the am or pm part -->
<xsl:choose>
<xsl:when test="$hours < 12"> <!-- if we are 01-11 -->
<xsl:value-of select="substring(concat('0', $hours + 1), string-length(concat('0', $hours + 1)) - 1, 2)"/> <!-- add an hour and repad the string with leading zero, messy -->
</xsl:when>
<xsl:otherwise>
<xsl:text>01</xsl:text> <!-- we were 12, so just use 01 -->
</xsl:otherwise>
</xsl:choose>
<xsl:value-of select="substring($time, 3,4)"/> <!-- pull the minutes forward -->
<xsl:choose>
<xsl:when test="not($hours = 11)"> <!-- if we were not 11 for hours we keep the same am/pm -->
<xsl:value-of select="$mer"/>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when test="$mer = 'pm'"> <!-- otherwise we flip it -->
<xsl:text>am</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>pm</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
<xsl:text> ET</xsl:text>
+1作品。如果将它转换为可重用的函数/调用模板会更好。这将使它更容易与文本内联使用。 “您的请求已在[电话模板]上收到,并将被处理。” – RegEdit
将其包装在命名模板中将是可能的。此时,可能需要修改逻辑,以便它可以处理可变偏移量,而不仅仅是ET的固定一小时偏移量。 –
有一个在XSLT 1.0此没有内置的方法。无论如何,这将是相当微不足道的 - 除了你的时间输入是12小时格式。这使得该方法相当繁琐,所以我关分割到一个处理的模板:
<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="/">
<node>
<xsl:attribute name="time">
<xsl:call-template name="time-offset">
<xsl:with-param name="time" select="node/@time"/>
</xsl:call-template>
</xsl:attribute>
</node>
</xsl:template>
<xsl:template name="time-offset">
<xsl:param name="time"/>
<xsl:param name="offset" select="1"/>
<xsl:param name="h12" select="substring($time, 1, 2)"/>
<xsl:param name="pm" select="contains($time,'p') or contains($time,'P')"/>
<xsl:param name="h24" select="$h12 mod 12 + 12*$pm"/>
<xsl:param name="newH24" select="($h24 + $offset + 24) mod 24"/>
<xsl:param name="newH12" select="($newH24 + 11) mod 12 + 1"/>
<xsl:param name="am.pm" select="substring('AMPM', 1 + 2*($newH24 > 11), 2)"/>
<xsl:value-of select="concat(format-number($newH12, '00'), substring($time, 3, 4), $am.pm, ' ET')"/>
</xsl:template>
</xsl:stylesheet>
当上述的样式表应用到例如输入:
<node time="12:14 am CT" />
结果是:
<?xml version="1.0" encoding="UTF-8"?>
<node time="01:14 AM ET"/>
“CT”的意思是[中央时区](http://en.wikipedia.org/wiki/Central_Time_Zone_%28North_America%29)?如果是这样,您只需要在给定时间内添加一小时以将其转换为东部时区(假设您的兴趣区域遵守相同的DST规则)。你在使用XSLT 1.0还是2.0? –
是的,中央时区。 XSLT 1.0 – RegEdit
你可以发布一个XML输入的例子吗? –