I have to create a date string in DDMMYYYY format using xquery. The date input to my xquery will be like "2004-05-02T00:00:00+01:00". As of now i am using the following solution to get the required fromat(02052004),
$dateString:= concat(substring($dateInput, 9, 2), substring($dateInput, 6, 2), substring($dateInput, 1, 4));
Is there any other way or inbuilt function using which i can convert a date to required string format?
If you've got access to XQuery 3.0, you can take advantage of format-dateTime($date, $picture):
let $date := xs:dateTime("2004-05-02T00:00:00+01:00")
return format-dateTime($date, "[D,2][M,2][Y,4]")
If you haven't (only XQuery 1.0), you still can use a more semantic version. As it also has no format-number(...) function, I'm using some prepared functions from functx:
declare namespace functx = "http://www.functx.com";
declare function functx:pad-integer-to-length
( $integerToPad as xs:anyAtomicType? ,
$length as xs:integer ) as xs:string {
if ($length < string-length(string($integerToPad)))
then error(xs:QName('functx:Integer_Longer_Than_Length'))
else concat
(functx:repeat-string(
'0',$length - string-length(string($integerToPad))),
string($integerToPad))
} ;
declare function functx:repeat-string
( $stringToRepeat as xs:string? ,
$count as xs:integer ) as xs:string {
string-join((for $i in 1 to $count return $stringToRepeat),
'')
} ;
let $date := xs:dateTime("2004-05-02T00:00:00+01:00")
let $date := xs:date($date)
return string-join((
functx:pad-integer-to-length(day-from-date($date), 2),
functx:pad-integer-to-length(month-from-date($date), 2),
functx:pad-integer-to-length(year-from-date($date), 4)
))
Decide on your own if you prefer the more bulky, but semantic version or simple string manipulation. Be aware that time zones might lead to different results depending on which one you choose.
If you are using a XQuery 1.0 processor it will be slighlty complicated. There are functions like fn:day-from-dateTime() available, but the would return a single number for a numer below 10, which is quite likely not what you want.
You can write a simply padding function
declare function local:pad($number as xs:integer) as xs:string
{
if ($number<10)
then concat("0", $number)
else xs:string($number)
};
and use it to construct the date
concat(
local:pad(day-from-dateTime(xs:dateTime($dateInput))),
local:pad(month-from-dateTime(xs:dateTime($dateInput))),
year-from-dateTime(xs:dateTime($dateInput))
)
If your processor supports XQuery 3.0, the fn:format-dateTime() is available and allows easier formatting. The formatting rules are available at http://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/#rules-for-datetime-formatting. For your desired output the following should work:
fn:format-dateTime(xs:dateTime($dateInput),"[D01][M01][Y}")
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