# Difference in two timestamp fields

**URL:** <https://discuss.elastic.co/t/difference-in-two-timestamp-fields/232151>\
**Category:** Kibana\
**Created:** [May 12, 2020, 7:08am UTC](https://discuss.elastic.co/t/difference-in-two-timestamp-fields/232151 "2020-05-12T07:08:00Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![jsanz](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jsanz/32/53734_2.png) [@jsanz](https://discuss.elastic.co/u/jsanz)\
**Post date:** [May 13, 2020, 8:55am UTC](https://discuss.elastic.co/t/difference-in-two-timestamp-fields/232151/2 "2020-05-13T08:55:48Z")

</div>

This will be helpful

> [@Kibana painless- Difference in dates in days](https://discuss.elastic.co/t/kibana-painless-difference-in-dates-in-days/169201/2):
>
> You could do something like the following: return (doc['date2'].value.millis - doc['date1'].value.millis) / 1000 / 60 / 60 / 24;

I tried a simple script query with the sample ecommerce dataset and works as expected. I just changed the `.millis` property by the recommended method `.toInstant().toEpochMilli()`.

```
GET kibana_sample_data_ecommerce/_search
{
    "_source": ["products.created_on", "order_date"],
    "size": 2,
    "script_fields": {
      "difference": {
        "script": {
          "source": "(doc['order_date'].value.toInstant().toEpochMilli() - doc['products.created_on'].value.toInstant().toEpochMilli()) / 1000 / 60 / 60 / 24"
        }
      }
    }
}

```

With the result:

```
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 4675,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "kibana_sample_data_ecommerce",
        "_type" : "_doc",
        "_id" : "XAGPn3AB9W_0WIVNAOX7",
        "_score" : 1.0,
        "_source" : {
          "order_date" : "2020-03-16T09:28:48+00:00",
          "products" : [
            {
              "created_on" : "2016-12-26T09:28:48+00:00"
            },
            {
              "created_on" : "2016-12-26T09:28:48+00:00"
            }
          ]
        },
        "fields" : {
          "difference" : [
            1176
          ]
        }
      },
      {
        "_index" : "kibana_sample_data_ecommerce",
        "_type" : "_doc",
        "_id" : "XQGPn3AB9W_0WIVNAOX7",
        "_score" : 1.0,
        "_source" : {
          "order_date" : "2020-03-15T21:59:02+00:00",
          "products" : [
            {
              "created_on" : "2016-12-25T21:59:02+00:00"
            },
            {
              "created_on" : "2016-12-25T21:59:02+00:00"
            }
          ]
        },
        "fields" : {
          "difference" : [
            1176
          ]
        }
      }
    ]
  }
}

```

---

_[View the full topic](https://discuss.elastic.co/t/difference-in-two-timestamp-fields/232151)._
