Milister
Milister

Reputation: 658

Compare datetime inside variable with current datetime

I have the following line:

 for custom_field in $(jq -r '.issues[] | .fields.created' 1.json
); do
      echo $custom_field

done

Output:

2018-03-06T21:24:41.000+0000
2018-03-06T22:48:47.000+0000

How to compare current datetime with each output and if it's older than 3 hours to print "old"?

Upvotes: 2

Views: 215

Answers (2)

tripleee
tripleee

Reputation: 189739

Given input like

{ "issues":
 [{"id": 1, "fields": {"created": "2018-03-06T21:24:41.000+0000"}},
  {"id": 2, "fields": {"created": "2018-03-06T22:48:47.000+0000"}},
  {"id": 3, "fields": {"created": "2018-03-09T22:48:47.000+0000"}}]}

you can use the built-in date manipulation functions to print the old records with something like

jq -r '(now-3600*3) as $when | .issues[] |
  select(.fields.created | strptime("%Y-%m-%dT%H:%M:%S.000+0000") | mktime < $when) |
[.id, .fields.created, "old"]' 1.json

where the last line probably needs tweaking to produce exactly the output you want.

Upvotes: 2

jas-
jas-

Reputation: 1801

It is much easier to convert first and subtract the three hours.

Example below converts to seconds and prints true if condition is met.

date_in_seconds=$(date -d $custom_field +"%s"); [ ${date_in_seconds} -gt 259200 ] && echo true;

For non GNU versions of the date command you can use the following;

date_in_seconds=$(date -j -f '%Y-%m-%d %H:%M:%S' "2016-02-22 20:22:14" '+%s')

Keep in mind that the EPOCH will rollover 1 Jan 2036.

Upvotes: 1

Related Questions