我第一次使用 XSLT。我需要将日期从 dd/mm/yyyy 转换为 yyyy-mm-dd .以下是我的代码。
<xsl:element name="transactionDate">
<xsl:value-of select="concat(substring(col26,5,5), '-', substring(col26,3,1), '-', substring(col26,1,1))"/>
</xsl:element>
在上面的代码中,我能够将日期从 dd/mm/yyyy 转换为 yyyy-mm-dd,但是当日期为两位数时,它不起作用。
有人可以建议吗?
提前谢谢。
如果col26
包含dd/mm/yyyy
格式的日期,则表达式应为:
<xsl:value-of select="concat(substring(col26, 7, 4), '-', substring(col26, 4, 2), '-', substring(col26, 1, 2))"/>
不确定"当日期达到两位数时"是什么意思。以上假设输入中的天数和月份以零填充,每位为 2 位数字。否则,格式不dd/mm/yyyy
。
添加:
如果日期是2/4/2019,那么它(我的代码(工作正常
如果日期可以2/4/2019
,那么您的格式是 d/m/y
,而不是 dd/mm/yyyy
。要将其转换为yyyy-mm-dd
,请尝试:
<transactionDate>
<xsl:variable name="d" select="substring-before(col26, '/')" />
<xsl:variable name="m" select="substring-before(substring-after(col26, '/'), '/')" />
<xsl:variable name="y" select="substring-after(substring-after(col26, '/'), '/')" />
<xsl:value-of select="format-number($y, '0000')" />
<xsl:value-of select="format-number($m, '-00')" />
<xsl:value-of select="format-number($d, '-00')" />
</transactionDate>
添加#2:
很抱歉通知您,在日期字段中的值为"20/12/2019 9:24:00 AM",时间也以csv格式出现
你没有早点透露这一信息,确实令人遗憾。
如果您的输入格式为 d/m/y h:mm:ss xm
,请使用:
<transactionDate>
<xsl:variable name="date" select="substring-before(col26, ' ')" />
<xsl:variable name="d" select="substring-before($date, '/')" />
<xsl:variable name="m" select="substring-before(substring-after($date, '/'), '/')" />
<xsl:variable name="y" select="substring-after(substring-after($date, '/'), '/')" />
<xsl:value-of select="format-number($y, '0000')" />
<xsl:value-of select="format-number($m, '-00')" />
<xsl:value-of select="format-number($d, '-00')" />
</transactionDate>
演示:https://xsltfiddle.liberty-development.net/pPzifpU