Search code examples
datetimesparql

Determining Day Of Week For Datetime in SPARQL


I have a graph I am trying to filter for a report by day of week. For instance, I wish to find all the instances where they occurred on a Tuesday. Is there a way to either format the datetime field into day of week or filter by day of week directly on the datetime field?


Solution

  • You can also determine the day of week in standard SPARQL if you provided a bit of background knowledge. The query needs a reference date preceding your dates and the day of week at this date.

    PREFIX xsd:  <http://www.w3.org/2001/XMLSchema#>
    
    SELECT ?date ?dayName
    WHERE {
      # Sample dates
      VALUES ?date {
        "1961-08-04"^^xsd:date
        "1986-04-03"^^xsd:date
      }
      # Compute days since a reference date
      # This works in Virtuoso, which returns the difference in days.
      # For example, Fuseki returns xsd:duration instead.
      BIND (?date - "1900-01-01"^^xsd:date AS ?days)
      # Compute modulo by 7 without a modulo operator
      BIND (floor(?days - (7 * floor(?days/7))) AS ?mod)
      VALUES (?mod ?dayName) {
             (0    "Monday") # 1900-01-01 was Monday
             (6    "Tuesday")
             (5    "Wednesday")
             (4    "Thursday")
             (3    "Friday")
             (2    "Saturday")
             (1    "Sunday")
      }
    }