Compare two date/timestamp in Kibana

Hello,

Is it possible to create a new scripted field by subtracting a date from current time?
for example:

current timestamp - doc['OpenTime'].value

I tried following code but didn't work.

doc['@timestamp'].value - doc['OpenTime'].value

You can get the current timestamp using new Date().getTime(). I was able to calculate the difference in millis using the following painless scripted field:

new Date().getTime() - doc['@timestamp'].value.getMillis()

Using doc['@timestamp'].value won't give you the current datetime in real time. In my example, my index has a field called @timestamp which is when the docs were indexed.

1 Like

Thanks Stacey for your reply.

new Date().getTime() works fine for me however when I tried to get time difference, it's not working for me. I used same code new Date().getTime() - doc['@timestamp'].value.getMillis(). I have done following, please let me know if I am doing something wrong here.

Language: painless
Type: Number
Format: default
Popularity: 0
Script: new Date().getTime() - doc['@timestamp'].value.getMillis()

I am using Kibana version 5.3.0

Facing following error.

I think you want

new Date().getTime() - doc['OpenTime'].value.getMillis()

since in your example your time field looks to be called OpenTime. I only used @timestamp as that's specific to the index I'm testing this with.

If that doesn't work, try

new Date().getTime() - doc['OpenTime'].value

I switched to 5.3 and in that version the first variation didn't work as my field appears to be a long type and not a joda MutableDateTime object, so it may have changed in a more recent version.

1 Like

Yes, you are right I wanted new Date().getTime() - doc['OpenTime'].value and this works perfectly.

Adding to this, i wanted to calculate days difference between OpenTime and Current time. So I used following code and works fine for me.

def diff = new Date().getTime() - doc['OpenTime'].value;
return diff / 1000 / 60 / 60 / 24

Thanks for your help.

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.