Convert Date to String using Painless

HI Team,

We are on ELK 6.2.3. We have a field "ETime" which is in UTC format (2018-03-27 06:38:08.496Z).

We would like to convert this time to HH:mm:ss and convert that to string using Painless language to use it in some other visualization type. I tried with the below code using SimpleDateFormat but get an error - Unable to parse.

Code:

def mydate = doc['ETime'].value;
def df = new SimpleDateFormat('HH:mm:ss');
String finaldate = df.format(mydate);
return finaldate;

[Help - https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html24]

Could you please help on how to convert this field and have it as Scripted Field. Correct me if there are any mistakes in the code.

The error that you are going to get with this script is:

"caused_by": {
  "type": "illegal_argument_exception",
  "reason": "Cannot format given Object as a Date"
}

When I search in Google to find solutions to that error, I see an article that says the SimpleDateFormat#format method expects to have a Date input, but instead a String has been given.

You'll need to first parse the date field (string) as a Date object, then format that date object. It'll be something like:

def dateString = doc['date'].value;

def inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
def myDate = inputFormat.parse(dateString);

def outputFormat = new SimpleDateFormat('HH:mm:ss');

return outputFormat.format(myDate);

Hi @tsullivan, thanks for the response and pointing out the mistake in the code.
Will try this out.

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