【问题标题】:Get current time in the format YYYY-MM-DD-HH.MI.Sec.Ms using XSLT使用 XSLT 以 YYYY-MM-DD-HH.MI.Sec.Ms 格式获取当前时间
【发布时间】:2014-07-09 15:53:22
【问题描述】:

我有以下 xml:

<root>
<Test>tested</Test>
</root>

现在,我想使用 XSLT 将格式为 YYYY-MM-DD-HH.MI.Sec.Ms 的当前日期时间戳添加到上述 xml 的新节点。例如,我生成的 xml 应如下所示:

<root>
<Test>tested</Test>
<dateTimeStamp>2014-05-21-01.25.32.000000</dateTimeStamp> 
</root>

有人可以帮我解决这个问题吗?

能否请您也添加 XSLT 1.0 的代码,以便我找出不同之处?我会为此 +1。

【问题讨论】:

标签: xml date datetime xslt


【解决方案1】:

你可以使用format-dateTime()...

XSLT 2.0

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/*">
        <xsl:copy>
            <xsl:copy-of select="@*|node()"/>
            <dateTimeStamp>
                <xsl:value-of select="format-dateTime(current-dateTime(),'[Y0001]-[M01]-[D01]-[H01].[m01].[s].[f]')"/>
            </dateTimeStamp>
        </xsl:copy>        
    </xsl:template>

</xsl:stylesheet>

输出

<root>
   <Test>tested</Test>
   <dateTimeStamp>2014-05-21-01.44.58.312</dateTimeStamp>
</root>

请参阅http://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/#rules-for-datetime-formatting 了解更多信息。

【讨论】:

  • 丹尼尔,效果很好。谢谢。您能否也添加 XSLT 1.0 的代码,以便我找到差异?我会为此奖励+1。谢谢
【解决方案2】:

尝试类似:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

    <xsl:strip-space elements="*"/>

    <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/root">
        <xsl:variable name="timeNoMs" select="translate(substring-before(substring-before(string(current-time()), '+'), '.'), ':', '.')"/>
        <xsl:variable name="timeMs" select="format-number(number(substring-after(substring-before(string(current-time()), '+'), '.')), '##0000')"/>
        <xsl:copy>
            <xsl:copy-of select="node()|@*"/>
            <dateTimeStamp><xsl:value-of select="concat(substring-before(string(current-date()), '+'), '-', $timeNoMs, $timeMs)"/></dateTimeStamp>
        </xsl:copy>
    </xsl:template>    

</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-06
    • 2010-11-30
    • 2018-04-07
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    相关资源
    最近更新 更多