Friday, July 18, 2008

XPath: First Weekday Following a Given Date

You are given a date d. If that date does not fall on a weekday, you would like to find the first weekday date that follows d. The following XPath code will do the trick:

for $start in xs:date('2008-07-19') return
(: Get date plus two following dates, i.e. candidate dates :)
(for $i in (0 to 2) return
$start + xs:dayTimeDuration(concat('P', $i, 'D')))
(: Only keep date on week dates :)
[number(format-date(., '[F0]', 'en', (), ())) le 5]
(: Take first possible date :)
In the above expression, the date (7/19/2008) is just provided as a string, so you can quickly test this, for instance in the XPath Sandbox. The expression uses the XSLT format-date() function to find the day of the week for a given date. Unfortunately this function is strictly speaking not an XPath function, but some engine will bend the rule and still expose it to you for convenience, as does Orbeon Forms.

You can also check if a given date is a weekday with:
'[F0]', 'en', (), ())) le 5