Using the format-date() Function
Our last enhancement is to use the new format-date()
function to format the
date of the purchase order. This is an addition to the function of our
XSLT 1.0 stylesheet; everything else we’ve done here has duplicated
XSLT 1.0 function in a much simpler way. The date of each purchase
order is stored as three attributes named year
, month
, and day
. We’ll use the values of those three
attributes to create a new xs:date
value, then we’ll use format-date()
to format the
value.
To create a new xs:date
value, we need a string in the format yyyy-mm-dd
. xs:date('2006-10-10')
is a valid call to the
xs:date
constructor. To complicate
things, the month and day values must have two
digits. In other words, xs:date('2006-9-8')
raises an error. Our
purchase orders don’t necessarily have two-digit month and day values,
so we’ll have to write code to add a leading zero if either value is
less than 10. Here’s how we do this:
<xsl:variable name="monthValue" as="xs:string" select="if (date/@month < 10) then concat('0', date/@month) else date/@month"/> <xsl:variable name="dayValue" as="xs:string" select="if (date/@day < 10) then concat('0', date/@day) else date/@day"/>
We compare the value of the attributes to 10
; if they’re smaller, we add the string
'0'
to the value. (Notice that the
two variables we’re creating here are of datatype xs:string
.) In this code, we have to use the
<
operator because we’re
comparing a node to a number. If we want to use the lt
operator, ...
Get XSLT, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.