Mayank Tripathi
Mayank Tripathi

Reputation: 378

How to convert xs:dateTime to xs:string in xslt

We are trying to convert date-Time from GMT to EST so that we following this approach.

  1. we are getting date-time without timezone in String and then appending time zone to it.
  2. After appending timezone, converting DateTime to EST from GMT.
  3. adjust-dateTime-to-timezone will return date time in EST with timezone.
  4. Now, we want to return EST date-time without timezone as String from this template.

Here is my xsl -

<xsl:template name="convertGMTToEST">
          <xsl:param name="gmtDateTime" />
            <xsl:variable name="gmtDateTimeWithTimeZone" select="concat($gmtDateTime,'+00:00')"/>
            <xsl:variable name="estDateTime" select="adjust-dateTime-to- 
           timezone(xs:dateTime($gmtDateTimeWithTimeZone),xs:dayTimeDuration('-PT5H'))"/>
            
            <xsl:value-of select="substring-before($estDateTime, '-')"/>
    </xsl:template>

Expected Output- we want to return EST dateTime without timezone in xs:String.
How can we convert xs:dateTime to xs:string before doing substring-before as first argument of fn:substring-before() is xs: string;
Note- we are using xslt 2.0 processor.

Upvotes: 0

Views: 3582

Answers (2)

Michael Kay
Michael Kay

Reputation: 163272

The direct answer to the question "How can we convert xs:dateTime to xs:string" is: use the string() function. But as @michael.hor257k points out, I think you're making things unnecessarily complicated.

Upvotes: 0

michael.hor257k
michael.hor257k

Reputation: 116958

I think you are over-complicating this. The difference between GMT and EST is a constant 5 hours. Why don't you simply subtract 5 hours from the given dateTime and be done? For example:

XML

<input>
    <string>2020-01-01T20:45:15</string>
    <string>2020-01-01T04:15:30</string>
</input>

XSLT 2.0

<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="/input">
   <output>
        <xsl:for-each select="string">
            <string>
                <xsl:value-of select="xs:dateTime(.) - xs:dayTimeDuration('PT5H')"/>
            </string>
        </xsl:for-each>
    </output>    
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<output>
   <string>2020-01-01T15:45:15</string>
   <string>2019-12-31T23:15:30</string>
</output>

Upvotes: 1

Related Questions