Hi Can anyone advise how I can get Age from a dateofbirth datetime field to use in Kibana displays? I have created a couple of scripted fields to get DayofWeek and TimeofDay from another date field so I'm thinking this is the way to go but I'm not sure of the syntax for age?
Guessing its to do with the difference between DOB and now(sysdate?)
Thanks in advance
We can calculate the number of years between two DateTime's using Java's Period class. To create a Period we'll turn the timestamp in the doc and the current time into two LocalDate objects. doc['@timestamp'].value
returns a JodaCompatibleZonedDateTime which has a toLocalDate
method. We can get a LocalDate representing the current time with Instant.ofEpochMilli(System.currentTimeMillis()).atZone(doc['@timestamp'].value.getZone()).toLocalDate()
. Finally we can get the years from the Period object with the getYears
method. Putting it all together we get:
return Period.between(
doc['@timestamp'].value.toLocalDate(),
Instant.ofEpochMilli(System.currentTimeMillis()).atZone(doc['@timestamp'].value.getZone()).toLocalDate()
).getYears()
Thanks for the reply
I tried to use this but am getting an error (I presume you meant in a scripted field?)
Even when just using timestamp I get this
"script": "return Period.between(\n doc['@timestamp'].value.toLocalDate(), \n Instant.ofEpochMilli(System.currentTimeMillis()).atZone(doc['@timestamp'].value.getZone()).toLocalDate() \n).getYears()",
"lang": "painless",
"caused_by": {
"type": "illegal_argument_exception",
"reason": "**Unable to find dynamic method [toLocalDate] with [0] arguments for class [org.joda.time.MutableDateTime**]."
however the field I actually want is called DOB so tried this too
It says There's an error in your script
{
"root_cause": [
{
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"return Period.between(\n doc['DOB'].value.toLocalDate(), \n Instant.ofEpochMilli(System.currentTimeMillis()).atZone(doc['DOB'].value.getZone()).toLocalDate() \n).getYears()",
" ^---- HERE"
Is it something to do with my dates being datetime or the format of them?
timestamp looks like this
"_id": "gnJMpGkBO7EWFsePkxo3",
"myScriptedField": [
"2019-03-22T07:27:53.042Z"
]
DOB like this
"_id": "gnJMpGkBO7EWFsePkxo3",
"myScriptedField": [
"2004-01-17T23:00:00.000Z"
]
Many thanks
What version of ES are you using?
This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.