How can I format a seconds value in a table?

Hello

I have a value in seconds that I want to show in a more readable format like HH:MM:SS.

How can I do it?

Thank you

Hi,

I think you can do this by either using a data formatter (https://www.elastic.co/guide/en/kibana/current/managing-fields.html) or by creating a scripted field (https://www.elastic.co/guide/en/kibana/current/scripted-fields.html) with something like

def dateFormat = new SimpleDateFormat("HH:mm:ss");
return dateFormat.format(doc['YOUR_TIME_FIELD'].value);

Thank you.

Should the scripted field be formatted as date?

Hey @Hugo_Pires

Yes it should.
I've built an example with some demo data that you can check in the following image:

In my demo data timestamp was of a difference type so I've followed other approach.

Hello again and thank you

In both solutions, I got a script error... Could you help?

Hi,

The final solution will depend on the underlying type of the field for which you're applying the scripted field against.
Could you share more information about that field and the script error you're facing?

Cheers

Sure

The underlying field is a number representing the value in seconds. I want to show it in a HH:mm:ss format

The error is:

"caused_by": {
     "type": "illegal_state_exception",
     "reason": "A document doesn't have a value for a field! Use doc[<field>].size()==0 to check if a document is missing a field!"
    }

I 've used the following code:

def dateFormat = new SimpleDateFormat("HH:mm:ss");
return doc['call_time'].size()==0 ? '' : dateFormat.format(doc['call_time'].value);

but it returns always 00:00:00

Could you help me?

@Hugo_Pires that is probably happening because you still have invalid values on call_time then when formatted as a date time format will just be 0.

Could you try something like

def dateFormat = new SimpleDateFormat("HH:mm:ss");
return doc['call_time'].size() !=0 && doc['call_time'].value > 0  ? dateFormat.format(doc['call_time'].value) : '';

Cheers

sorry, the problem is the same

call_time: 3
call_time_ts: 00:00:00

Thank you

@Hugo_Pires maybe what you're trying to do is not formatting a timestamp but instead formatting a duration. If that is the case maybe you can just simple do:

def call_time = doc['call_time'].value;
def duration = call_time >= 0 ? call_time : 0;
def hour = duration / 3600;
def minute = (duration % 3600) / 60;
def sec = duration % 60;
return String.format('%02d:%02d:%02ds', new def[] {hour, minute, sec})

Cheers

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