首页 > 解决方案 > 将 ISO8601 时间转换为 12 小时格式

问题描述

XSLT 2.0- 氧气

<string>encounterDatetime</string>
<string>2020-04-05T16:36:00.000-0500</string>
<string>patient</string>

我需要使用 XSLT 来转换它并在主模板中显示它。我已经用 x 路径做了一些工作来找到时间函数的每一部分。除此之外,恐怕我不知道如何进行。不可否认,我在 xml 方面很糟糕。我只提供了一点点数据。到目前为止,这是我所拥有的,我想出了 x 路径(我认为),但我被卡住了。如果您有更好的解决方案,我不在乎是否必须摆脱以下代码。

<xsl:template name="TFTime">
    <xsl:param name="TS"/>
    <xsl:variable name="H" select="number(substring($TS, 1, 2))"/>
    <xsl:variable name="M" select="number(substring($TS, 4, 2))"/>
    <xsl:variable name="S" select="number(substring($TS, 7, 2))"/>

    <!-- how to proceed? -->

</xsl:template>

任何帮助将不胜感激。我尝试过使用 W3 学校,但我觉得我的技能还不足以理解他们的解释。

预期的输出将是这样的:

晚上 11:00/上午

我不需要秒数,我已经想出了如何提取日期。

在纸上 t=0 然后 t+12

t>12 从时间中减去 12

如果小于 12,则什么也不做。

我有一种感觉,一旦我到达需要添加 AM 和 PM 的部分,为了方便起见,我应该在这里使用 11

标签: xmlxsltxpath

解决方案


简而言之,formate-dateTime()如果您在 XSLT 2.0(或更高版本)中工作,那么至少,如果您在 XSLT 2.0(或更高版本)中工作,那么该函数就是您正在寻找的,因为它在 XSLT 1.0 中不可用。

在这种情况下,最大的问题是,您的 dateTime String 不符合W3C XML Schema Definition Language (XSD) 1.1 Part 2: Datatypesxs:dateTime中定义的数据类型,因为它需要格式化时区偏移量,即在上面的示例中。有两种方法可以处理这个问题:(+|-)HH:mm-05:00

  1. 考虑到您不需要时区信息,您可以将其从字符串中剥离,因为xs:dateTime它是唯一可剥离的参数。
  2. 如果您需要时区信息,则必须:在小时和分钟之间插入分隔符。

我将继续使用 »1.«:

<xsl:template name="TFTime">
        <!-- a string that looks like a xs:dateTime except for the wron timezone formatting -->
        <xsl:param name="TS" as="xs:string"/>
        <!-- cut the wrongly formatted timezone from the string and convert the string to xs:dateTime  -->
        <xsl:variable name="TS-noTimezone" select="xs:dateTime(substring($TS, 1, 23))" as="xs:dateTime"/>
        <!-- apply function format-dateTime($input, $pictureString)
             [h01] hour in the 12h realm (h), as two-digit (01)
             :     just a string
             [m01] minutes (m), as two-digit (01)
             [PN,2-2] a.m. / p.m. format (P), in capitals (N), exactly 2 characters long (,2-2), as otherwise it would contain colons
        -->
        <xsl:value-of select="format-dateTime($TS-noTimezone, '[h01]:[m01] [PN,2-2]')"/>
    </xsl:template>

推荐阅读