I often find myself wanting to convert date strings into Unix timestamps using Neo4j’s APOC library and unfortunately some sources don’t use the format that apoc.date.parse expects.
e.g.
return apoc.date.parse("2012-11-12T08:46:15Z",'s')AS ts
Failed to invoke function `apoc.date.parse`:
Caused by: java.lang.IllegalArgumentException: java.text.ParseException: Unparseable date: "2012-11-12T08:46:15Z"
We need to define the format explicitly so the SimpleDataFormat documentation comes in handy. I tried the following:
return apoc.date.parse("2012-11-12T08:46:15Z",'s',"yyyy-MM-ddTHH:mm:ssZ")AS ts
Failed to invoke function `apoc.date.parse`:
Caused by: java.lang.IllegalArgumentException: Illegal pattern character 'T'
Hmmm, we need to quote the ‘T’ character we can’t just include it in the pattern. Let’s try again:
return apoc.date.parse("2012-11-12T08:46:15Z",'s',"yyyy-MM-dd'T'HH:mm:ssZ")AS ts
Failed to invoke function `apoc.date.parse`:
Caused by: java.lang.IllegalArgumentException: java.text.ParseException: Unparseable date: "2012-11-12T08:46:15Z"
The problem now is that we haven’t quoted the ‘Z’ but the error doesn’t indicate that not sure why!
We can either quote the ‘Z’:
return apoc.date.parse("2012-11-12T08:46:15Z",'s',"yyyy-MM-dd'T'HH:mm:ss'Z'")AS ts
%R%P%P%P%P%P%P%P%P%P%P%U
│"ts" │
%^%P%P%P%P%P%P%P%P%P%P%a
│1352709975│
└──────────┘
Or we can match the timezone using ‘XXX’:
return apoc.date.parse("2012-11-12T08:46:15Z",'s',"yyyy-MM-dd'T'HH:mm:ssXXX")AS ts
%R%P%P%P%P%P%P%P%P%P%P%U
│"ts" │
%^%P%P%P%P%P%P%P%P%P%P%a
│1352709975│
└──────────┘