XSLT日期格式转换从例如:2018年8月23日到2018年8月23日 [英] XSLT date format translation from eg: Aug 23 2018 to 23/08/2018

查看:112
本文介绍了XSLT日期格式转换从例如:2018年8月23日到2018年8月23日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用XSLT将日期格式从例如 2018年8月23日转换为 2018/08/23

How to do date format translation from e.g: Aug 23 2018 to 23/08/2018 using XSLT?

推荐答案

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

XSLT 1.0 does not have any date functions and you will need to use string manipulation functions to convert from one format to another and translate Aug to 08 using some processing logic.

XSLT 2.0 确实具有 format-date()函数,但是此函数期望的输入格式为 YYYY-MM-DD ,然后可以将其转换为以下格式示例

XSLT 2.0 does have format-date() function however the input format expected by this function is YYYY-MM-DD which can then be converted into formats shown in these examples.

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

You can use the below options for converting the date format

输入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 来匹配输入日期格式。您也可以使用其他方法。

Here the solution has used regex to match with the input date format. You can use a different approach as well.

<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]{{3}}) (\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>

这篇关于XSLT日期格式转换从例如:2018年8月23日到2018年8月23日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆