Search code examples
datedatetimesparqlrdf

SPARQL how to make DAY/MONTH always return 2 digits


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.


Solution

  • 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)
    }