ZonedDateTime.parse function not working for custom DateTimeFormatter

Below string to date time code is not working for me and it is returning empty array.
script1:

String datetime = '2021-03-25 08:41:22.011';
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
ZonedDateTime zdt = ZonedDateTime.parse(datetime, dtf);
return zdt;

when I changed the date format as below , the script is returning value.
script2:

String datetime = '2021-03-25 08:41:22.011 Z';
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS VV");
ZonedDateTime zdt = ZonedDateTime.parse(datetime, dtf);
return zdt;

I have to parse the time with format "yyyy-MM-dd HH:mm:ss.SSS" into a date time object . Any idea why the script1 is not working. I have tried many formatting options but none is working.

Are you manually entering values to String datetime ? Or this is just an example?
If not, where are the values coming from? Have samples of your raw data?
Cheers!

this is just an example. the values are coming from field doc[rtd.PARSER_TIME] of keyword data type. tried below script but empty array returned without any error.

String datetime = doc['rtd.PARSER_TIME'].value;
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
ZonedDateTime zdt = ZonedDateTime.parse(datetime, dtf);
return zdt

Thanks for the support..

Can you please show what you get when your script is like:

return doc['rtd.PARSER_TIME'].value

Some sample values ?!

it is returning document values as below.

to troubleshoot your issue, try

ZonedDateTime zdt = ZonedDateTime.parse(datetime, DateTimeFormatter.RFC_1123_DATE_TIME);

I suspect that your dtf object is wrong?

it is still returning empty array. what I observed is your input string data must have a 'Z' at the end otherwise it is returning empty array as result.

Script below is took from elastic search website and if you remove the 'Z' from the string and 'VV' from custom format it is returning empty array.

String datetime = 'custom y 1983 m 10 d 13 22:15:30 Z';
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"'custom' 'y' yyyy 'm' MM 'd' dd HH:mm:ss VV");
ZonedDateTime zdt = ZonedDateTime.parse(datetime, dtf);

Thanks
RK

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