Calculating Date Differentials In Neo4j

(Or calculating date differentials in any environment where you don’t have a date object)

For all the awesomeness of graph databases and Neo4j, the lack of a native date object seems a glaring omission and makes it difficult to calculate date differentials if you have two date strings and did not have the foresight to store it as a numeric value.

To get around this, you will need to either update all of your relevant nodes to calculate a numeric value which can be used for date operations.  Alternatively, you can use the magic of Julian Dates!  Why Julian?  Because it’s a continuous numeric value starting from the beginning of the Julian Period and can be “easily” calculated given a date string.

Consider a case where we have a task and a state and we want the average number of days between the created date of the task and the created date of the state.

In the sample Cypher below, the dates are stored in yyyy-MM-dd format:

The actual algorithm is included below from the Wiki article:

Calculating a Julian Day value from a Gregorian Date

You may also like...

5 Responses

  1. Have you seen the apoc library with it’s apoc.date.parse and apoc.date.format functions(3.1) / procedures (3.0) ?

    https://neo4j-contrib.github.io/neo4j-apoc-procedures/#_date_time_support

    MATCH (task:Task)-[:HAS_STATE]-(state:TaskState)
    WITH apoc.date.parse(task.CreatedUtc,’s’,’yyyy-MM-dd’) as task_s,
    apoc.date.parse(state.CreatedUtc,’s’,’yyyy-MM-dd’) as state_s
    RETURN apoc.date.format(state_s – task_s, ‘s’, ‘D’) as deltaDays