0

I have these two nodes in XML:

<firstregistrationdate>01.10.2016.</firstregistrationdate>

<currentdate>14.10.2021.</currentdate>

And I would like to calculate days or years between them so if anybody has an idea how to do that it would be very helpful.

Thanks!

Tony Graham
  • 7,306
  • 13
  • 20
  • Well, which is it: days or years? And how does one calculate years between 2 dates? Fully elapsed years, fractional average years, or ...?? – michael.hor257k Oct 14 '21 at 10:51
  • For example, if we are calculating years to be like this: 2021 - 2016 = 5 If that is not possible to calculate days and then to divide by number of days in a year to get how many years that is.. (we will use 365). – Zoran Maćešić Oct 14 '21 at 10:53
  • It is possible to calculate the number of days. It is also possible to subtract one year from another. You just need to decide which one you want. Note that dividing the number of days by 365 is not the same as subtracting the years. – michael.hor257k Oct 14 '21 at 11:15

1 Answers1

2

If you only want the difference between the two years, you could do simply:

<xsl:variable name="startyear" select="substring(firstregistrationdate, 7, 4)"/>
<xsl:variable name="endyear" select="substring(currentdate, 7, 4)"/>
<result>
        <xsl:value-of select="xs:integer($endyear) - xs:integer($startyear)"/>
</result>

Demo: https://xsltfiddle.liberty-development.net/nbsuwEG

Added:

Calculating the difference in days between two dates is also fairly trivial in XSLT 2.0. The complication in your case is that the input dates are not in the expected YYYY-MM-DD format, so it is necessary to convert them first:

<xsl:variable name="startdate"  select="replace(firstregistrationdate, '(.{2})\.(.{2})\.(.{4})\.', '$3-$2-$1')"/>
<xsl:variable name="enddate"  select="replace(currentdate, '(.{2})\.(.{2})\.(.{4})\.', '$3-$2-$1')"/>
<result>
    <xsl:value-of select="days-from-duration(xs:date($enddate)-xs:date($startdate))"/>
</result>

Demo: https://xsltfiddle.liberty-development.net/nbsuwEG/1

michael.hor257k
  • 113,275
  • 6
  • 33
  • 51
  • Thanks! That worked! What about calculating days between those two dates? – Zoran Maćešić Oct 14 '21 at 11:56
  • I have added this to my answer, but as a rule you should ask one question at a time. – michael.hor257k Oct 14 '21 at 12:08
  • That would work for sure, but I'm getting a message: Could not find function: days-from-duration... Maybe this what my firm is using is xsl 1.0 but I don't know that for sure.. – Zoran Maćešić Oct 15 '21 at 09:09
  • @ZoranMaćešić You have tagged your question as XST 2.0 and my answer requires XSLT 2.0. If you don't know what version your processor supports, then start by finding out - see here how: https://stackoverflow.com/a/25245033/3016153 Then, if it turns out it's XSLT 1.0 only, post a new question. Or rather see: https://stackoverflow.com/a/22377178/3016153. – michael.hor257k Oct 15 '21 at 11:55