Search code examples
datetimexsltxslt-2.0

Need to reduce the 20 days prior from the input xml


Need to get the 20 days prior from the input xml element.

Input xml I'm having(year-month-day):

<section>
<Plans>
<Date>2022-01-01</Date>
</Plans>
</section>

<p>20 days back date: <keyword keyref="Cost:Date:date4"/></p>

XSL I'm using

<xsl:template match="keyword[contains(@keyref, 'Cost:Date:date4')]">
        <xsl:param name="section" as="element()" tunnel="yes">
            <empty/>
        </xsl:param>
        <keyword keyref="Cost:Date:date4">
            <xsl:call-template name="format_variable">
                <xsl:with-param name="cur_keyref" select="@keyref"/>
                <xsl:with-param name="cur_value"
                    select="$section//Plans/Date"/>
                <xsl:with-param name="cur_format" select="'date4'"/>
            </xsl:call-template>
        </keyword>
    </xsl:template>

<xsl:template name="format_variable">
        <xsl:param name="cur_keyref" as="xs:string">MISSING</xsl:param>
        <xsl:param name="cur_value" as="xs:string">MISSING</xsl:param>
        <xsl:param name="cur_format" as="xs:string">MISSING</xsl:param>
        <xsl:choose>
        <xsl:when test="$cur_format = 'date4'">
                <xsl:variable name="format" select="replace($cur_value, '(.{4})-(.{2})-(.{2})', '$2/$3/$1')"/>
                <xsl:value-of select="$format - xs:dateTime('P20D')"/>
            </xsl:when>
                <xsl:otherwise>
                <xsl:value-of
                    select="concat('MISSING_FORMAT_', $cur_keyref, '_', $cur_value, '_[', $cur_format, ']')"
                />
            </xsl:otherwise>
            </xsl:choose>
            </xsl:template>

When I'm trying the above code its showing the below error:

Invalid dateTime value "P20D" (Non-numeric year component)

Expected output is:

20 days back date: 12/12/2021

Solution

  • FWIW, I believe you are grossly overcomplicating this. The date in the input XML is in YYYY-MM-DD format; all you need to do is subtract a duration of 20 days from the given date - see demo here: https://xsltfiddle.liberty-development.net/6qaCymJ