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?
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 )
}
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.
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