Sun, 16 Oct 2005

XSLT to convert from a 24-hour timestamp

I had an XML file in which the timestamp for the file creation was in a 24-hour GMT format. I needed to convert the display date and time to be in the format of, "XXX as of 12:00 a.m., on Oct 17, 2005"

I found some of the code for converting the month name on the internet and the rest I hacked together to handle the 24-hour and GMT conversion.

Longer lines are split with a "\" character which should be removed before you use the code.

<!-- Start: XSLT date and time formatting template -->
<!-- e.g. 2005-07-18T17:59:30.187-08:00 -->

<xsl:template name="format-date-time">
  <xsl:param name="date" />
  <xsl:variable name="year" select="substring($date, 1, 4)" />
  <xsl:variable name="month" select="substring($date, 6, 2)" />
  <xsl:variable name="day" select="substring($date, 9, 2)" />
  <xsl:variable name="day2" select="translate($day, '0', '')" />
  <xsl:variable name="monthName" \ 
    select="substring('JanFebMarAprMayJunJulAugSebOctNovDec', \
    substring-before(substring-after($date,'-'),'-')*3-2,3)" />
  <xsl:variable name="hour24" select="substring($date, 12, 2) - 8" />
  <xsl:variable name="minute" select="substring($date, 15, 2)" />
  <xsl:variable name="second" select="substring($date, 18, 2)" />

  <xsl:variable name="hour12">
    <xsl:choose>
      <xsl:when test="$hour24 < 0">
        <xsl:value-of select="12 + $hour24" />
      </xsl:when>
      <xsl:when test="$hour24 = 0">
        <xsl:value-of select="12" />
      </xsl:when>
      <xsl:when test="$hour24 = 12">
        <xsl:value-of select="$hour24" />
      </xsl:when>
      <xsl:when test="$hour24 > 12">
        <xsl:value-of select="$hour24 - 12" />
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$hour24" />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  
  <xsl:variable name="meridiem">
    <xsl:choose>
      <xsl:when test="$hour24 < 0">p.m.</xsl:when>
      <xsl:when test="$hour24 >= 12">p.m.</xsl:when>
      <xsl:otherwise>a.m.</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>

  <xsl:value-of select="concat($hour12, ':', $minute, ':', $second, ' ', \
    $meridiem, ' on ', $monthName, ' ', $day2, ', ', $year)" />
  
</xsl:template>

<!-- End: XSLT date and time formatting template -->


posted: 00:24 | 0 comments | tags: , ,


© 2008 PlatosCave.net