Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SPARQL Calculating the difference between two date

Tags:

date

sparql

What is the function to calculate difference between two SPARQL xsd:dateTime ?

I have found a reference to datediff, but this is not working. Does such a built in function exist in SPARQL as it does with most other query languages?

like image 662
Shamim Hafiz - MSFT Avatar asked Sep 03 '13 22:09

Shamim Hafiz - MSFT


2 Answers

I found this post when I was searching on how to calculate an age in SPARQL. Thanks to Joshua Taylor for giving the correct hint. However I improved the code segment by adding an adjustment so it is not off by one year if the person hasn't had their birthday in the year of their death. I thought it might be useful to some, who find this post when searching for the topic, as I did.:

select ?age where { 
  bind( "1799-12-14"^^<http://www.w3.org/2001/XMLSchema#date> as ?death )
  bind( "1732-02-22"^^<http://www.w3.org/2001/XMLSchema#date> as ?birth )
  bind( year(?death) - year(?birth) - if(month(?death)<month(?birth) || (month(?death)=month(?birth) && day(?death)<day(?birth)),1,0) as ?age )
}
like image 34
Frog23 Avatar answered Oct 03 '22 05:10

Frog23


Some SPARQL engines may support date arithmetic directly. For instance, as mention in this answers.semanticweb.com question and answer, Jena supports date arithmetic, and you can subtract one date from another and get an xsd:Duration. Other implementations may support a datediff function. For instance, this Virtuoso example includes the use of bif:datediff. However, these are extensions and not guaranteed to be present in any particular SPARQL implementation.

For a more portable, though possibly less efficient solution, you can use the year to extract the year parts from a datetime. This lets you do, for instance,

select ?age where { 
  bind( "1799-12-14"^^<http://www.w3.org/2001/XMLSchema#date> as ?death )
  bind( "1732-02-22"^^<http://www.w3.org/2001/XMLSchema#date> as ?birth )
  bind( year(?death)-year(?birth) as ?age )
}

and get results

-------
| age |
=======
| 67  |
-------

This has the potential to be off by one, depending on the months and days of the two dates, but you can similarly work around this by using the month and day functions. This thread describes some of that sort of implementation.

like image 79
Joshua Taylor Avatar answered Oct 03 '22 03:10

Joshua Taylor