XML News from Wednesday, January 20, 2010

Parsing a date in the form "Wednesday, January 20, 2010" in XQuery:

xquery version "1.0";

declare function local:leading-zero($n as xs:decimal) as xs:string {
    let $result := if ($n >= 10) 
    then string($n)
    else concat("0", string($n))
   return $result
};

declare function local:parse-date($date as xs:string) as element() {
    let $day := normalize-space(substring-before($date, ","))
    let $string-date := normalize-space(substring-after($date, ","))
    let $year := normalize-space(substring-after($string-date, ","))
    let $month-day := normalize-space(substring-before($string-date, ","))
    let $months := ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
    
    let $month := substring-before($month-day, " ")
    let $day-of-month := number(substring-after($month-day, " "))
    
    return 
      <postdate>
        <day>{$day}</day>
        <date>{$year}-{local:leading-zero(index-of($months,$month))}-{local:leading-zero($day-of-month)}</date>
      </postdate>
};


local:parse-date("Monday, April 27, 2009")