Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert relative dates like "Today" and "Yesterday" to an XQuery date object?

Tags:

date

xquery

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".

like image 946
Siddhu Avatar asked May 30 '12 11:05

Siddhu


1 Answers

1. Parse the Date string

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")
};

2. Format the 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.

like image 190
Jens Erat Avatar answered Oct 11 '22 14:10

Jens Erat