Calculate Difference between 2 Dates in Scipted Field

Hi All,

I am trying to create a new scripted field by calculating the difference(in seconds) between 2 date in the following format `

October 15th 2018, 22:15:27.823

The two fields I am using are start_time and end_time.

I have tried various method covering both Painless and expression as language.
Every time I try I get different error.

Example:-

if(!doc['end_time'].empty)
{
return doc['end_time'].value - doc['start_time'].value
}

Error it gave is:-

"caused_by":{"type":"parse_exception","reason":"unexpected character '{' on line (1) position (26)","caused_by":{"type":"lexer_no_viable_alt_exception","reason":null}}}}]},"status":500}

Scenario 2:-
if(!doc['end_time'].empty){
doc['end_time'].date.secondOfMinute - doc['start_time'].date.secondOfMinute}

Error it gave is:-
"

caused_by":{"type":"parse_exception","reason":"unexpected token 'x' on line (1) position (4) was expecting one of "}}}]},"status":500 Preformatted text at http://10.23.213.99:5602/bundles/commons.bundle.js?v=16627:1:713755

I also tried to follow this:

**doc['end_time'].value - doc['start_time'].value**

** type: number**
** Format: Duration**
** InputFormat: seconds **
** OutputFormat: Human Readable**

Error was:-
"

caused_by":{"type":"class_cast_exception","reason":"Cannot apply [-] operation to types [org.joda.time.MutableDateTime] and [org.joda.time.MutableDateTime]."}}}]},"status":500}

Please let me know the solution with some code. I will greatly appreciate your help.
Thank you

Hi All,

Finally found what worked for me.

**if(!doc['end_time'].empty){**
**return doc['end_time'].value.getMillis() - doc['start_time'].value.getMillis();**
**}**

Note:-
Language:-Painless
Type:-Number
Format:-Durations
Input Parameters:- milliseconds
OutputParameter:- seconds
Decimal:-2

Popularity is 1. Don't know what it does though.

1 Like

Popularity just prioritizes that field in the field list on the left in Discover.

Okay Thank you :slight_smile:

I have asked 1 more topic in Kibana.
Can you please help me with that?

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