Create script - convert date to weeknumber

Hello,

I have been trying to create scripted field tha twoul convert date into week number but w/o success. I tried with this. Does not work.

doc['planDate'].value.getWeekNum()

I would appreciate some help.

Thanks!

Hi @Valerija,

Thanks for reaching out. What format are you expecting to see, and how is your date formatted currently? You may also want to check out our documentation on formatting.

Best,
Jessica

Hi,

Date is formatted as a date. What I would like to see is week number - for eg. CW 25 but I am not sure how to write a script to get the data is this format.

Thanks.
Violeta

Thanks for following up, @Valerija. Would ZonedDateTime work here? My first thought would be trying something similar to this:

POST /my_index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "script": {
            "script": {
              "source": """
                ZonedDateTime date = doc['planDate'].value.toInstant().atZone(ZoneId.of('UTC'));
                int week = date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
                int year = date.getYear();
                return week == 25 && year == 2024;
              """,
              "lang": "painless"
            }
          }
        }
      ]
    }
  }
}