XSLT日期格式翻译从例如:2018年8月23日到2018年8月23日

时间:2018-08-09 12:50:28

标签: xslt-1.0 xslt-2.0 date-format

如何使用XSLT将日期从Aug 23 2018转换为23/08/2018

1 个答案:

答案 0 :(得分:0)

XSLT 1.0 没有任何date函数,您将需要使用string操作函数将一种格式转换为另一种格式并将Aug转换为08使用某些处理逻辑。

XSLT 2.0 确实具有format-date()功能,但是此功能期望的输入格式为YYYY-MM-DD,然后可以将其转换为这些examples中所示的格式。

您可以使用以下选项转换日期格式

输入XML

<inputDate>Aug 23 2018</inputDate>

XSLT 1.0

<xsl:template match="inputDate">
    <xsl:variable name="day" select="substring(., 5, 2)" />
    <xsl:variable name="mth" select="substring(., 1, 3)" />
    <xsl:variable name="year" select="substring(., 8, 4)" />

    <!-- Convert 3 char month name to digit -->
    <xsl:variable name="month" select="string-length(substring-before('JanFebMarAprMayJunJulAugSepOctNovDec', $mth)) div 3 + 1" />
    <!-- Format the number to 2 digits -->
    <xsl:variable name="mthNum" select="format-number($month, '00')" />

    <formattedDate>
        <xsl:value-of select="concat($day,'/',$mthNum,'/',$year)" />
    </formattedDate>
</xsl:template>

XSLT 2.0

此处解决方案使用regex来匹配输入日期格式。您也可以使用其他方法。

<xsl:template match="inputDate">
    <!-- Define array of months -->
    <xsl:variable name="months" select="('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')" />
    <!-- Define regex to match input date format -->        
    <xsl:analyze-string regex="^(([A-Za-z]How to set extended file properties?) (\d\d) (\d\d\d\d))$" select=".">
        <!-- Align the regex groups according to the output format -->
        <xsl:matching-substring>
            <formattedDate>
                <xsl:value-of select="regex-group(3)" />
                <xsl:text>/</xsl:text>
                <xsl:value-of select="format-number(index-of($months, regex-group(2)), '00')" />
                <xsl:text>/</xsl:text>
                <xsl:value-of select="regex-group(4)" />
            </formattedDate>
        </xsl:matching-substring>
    </xsl:analyze-string>
</xsl:template>

这两个模板的输出

<formattedDate>23/08/2018</formattedDate>
相关问题