XQuery has a set of useful functions for date conversion. But how to convert relative dates like "Today" and "Yesterday" into the actual date?
For example "Today, 17:33" should be converted to "2012-05-30", and "Yesterday, 22:13" to "2012-05-29".
Parse the date string. I provided a small function which splits the word indicating the date off and parses it. I added some more convenient names for dates, but you can easily add more if neccessary, notice I convert to lower-case! It uses XQuery date and time functions for calculating the matching date.
declare function local:from-relative-date($string as xs:string) as xs:date {
switch (lower-case(substring-before($string, ",")))
case "today" return current-date()
case "yesterday" return current-date() - xs:dayTimeDuration('P1D')
case "day before yesterday" return current-date() - 2 * xs:dayTimeDuration('P1D')
case "tomorrow" return current-date() + xs:dayTimeDuration('P1D')
case "day after tomorrow" return current-date() + 2 * xs:dayTimeDuration('P1D')
default return error(xs:QName("XPTY0004"), "Unknown Date")
};
Now use the XQuery 3.0 function format-date(...)
(I hope your XQuery engine supports it, BaseX which I used for this example does) to format the date string like you need it:
format-date(local:from-relative-date("Yesterday, 22:13"), "[Y]-[M00]-[D00]")
If it doesn't, you will have to use year-from-date(...)
and according functions for month and day, use some number formatting and concatenate yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With