Home > database >  SPARQL how to make DAY/MONTH always return 2 digits
SPARQL how to make DAY/MONTH always return 2 digits

Time:05-19

I have a datetime in my SPARQL-query that I want to transform to a date. Therefore I do:

 BIND(CONCAT(YEAR(?dateTime), "-",MONTH(?dateTime), "-", DAY(?dateTime)) as ?date)  

This part of code works but returns for example 2022-2-3, I want it to be 2022-02-03. If the dateTime is 2022-11-23, nothing should change.

CodePudding user response:

You can take the integers you get back from the YEAR, MONTH, and DAY functions and pad them with the appropriate number of zeros (after turning them into strings):

PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
SELECT * WHERE {
    BIND(2022 AS ?yearInt) # this would come from your YEAR(?dateTime) call
    BIND(2 AS ?monthInt)   # this would come from your MONTH(?dateTime) call
    BIND(13 AS ?dayInt)    # this would come from your DAY(?dateTime) call

    # convert to strings
    BIND(STR(?yearInt) AS ?year)
    BIND(STR(?monthInt) AS ?month)
    BIND(STR(?dayInt) AS ?day)

    # pad with zeros
    BIND(CONCAT("00", ?year) AS ?paddedYear)
    BIND(CONCAT("0000", ?month) AS ?paddedMonth)
    BIND(CONCAT("00", ?day) AS ?paddedDay)

    # extract the right number of digits from the padded strings
    BIND(SUBSTR(?paddedYear, STRLEN(?paddedYear)-3) AS ?fourDigitYear)
    BIND(SUBSTR(?paddedDay, STRLEN(?paddedDay)-1) AS ?twoDigitDay)
    BIND(SUBSTR(?paddedMonth, STRLEN(?paddedMonth)-1) AS ?twoDigitMonth)
    
    # put it all back together
    BIND(CONCAT(?fourDigitYear, "-", ?twoDigitMonth, "-", ?twoDigitDay) as ?date)
}

CodePudding user response:

@gregory-williams gives a portable answer. An alternative is functions from F&O (XPath and XQuery Functions and Operators 3.1) "fn:format-...."

I'm not sure of the coverage in various triplestores - Apache Jena provides fn:format-number, which is needed for the question, but not fn-format-dateTime etc

See
https://www.w3.org/TR/xpath-functions-3/#formatting-the-number
https://www.w3.org/TR/xpath-functions-3/#formatting-dates-and-times

For example:

fn:format-number(1,"000") returns the string "001".

Apache Jena also has a local extension afn:sprintf using the C or Java syntax of sprintf:

afn:sprintf("d", 1) returns "001".

  • Related