问题
I have a variable caled Birthday
which will have value like 1/1/1970
. I need to calculate the age of a person based on that value. It would basically be the year from currentdate()-year
from the Birthday
variable. But How do I achieve this in XSLT? It is related to sharepoint DateView webpart. There is a field Birthday
of datetime
type. I need to extract age using that field. Can anyone point me in the right direction?
回答1:
My favorite resource for anything XSLT is Dave Pawson's website. One section deals with date manipulations in XSLT 2.0, and it seems to have very clear answers about how to do this.
Basically, you have to make sure that the date is in the correct format, then just use date subtraction:
xs:dateTime(actual-arrival) - xs:dateTime(xs:date(due-date))
(Note: I have not tested this.)
The XSLT 1 faqs are at this link.
回答2:
What you need is somewhat complex in XSLT 1.0, if you are more easy going with javascript you could do something like this:
<div id="mydate"></div>
<script type="text/javascript">
<![CDATA[
function datejs(datexslt) {
var date = datexslt.split('T')[0].split('-');
var time = datexslt.split('T')[1].split(':');
return new Date(date[1] + '/' + date[2] + '/' + date[0] + ' ' + time[0] + ':' + time[1] + ':' + time[2].substr(0, 2) + ' UTC');
}
var utc = datejs(']]><xsl:value-of select="@PublishedDate" /><![CDATA[');
//$('#mydate').text(utc);
]]>
</script>
回答3:
<xsl:variable name="Age">
<xsl:choose>
<xsl:when test="month-from-date(current-date()) > month-from-date($Birthday) or month-from-date(current-date()) = month-from-date($Birthday) and day-from-date(current-date()) >= day-from-date($Birthday)">
<xsl:value-of select="year-from-date(current-date()) - year-from-date($Birthday)" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="year-from-date(current-date()) - year-from-date($Birthday) - 1" />
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
来源:https://stackoverflow.com/questions/8792413/calculate-age-in-xslt-from-birthday