0

I have a date-time in a shell script variable. How can I compare it with current timestamp and find out how many minutes the difference is between these two dates in a shell script?

The variable I have in a shell script has a value like 08/16/2019 15:34:00.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
v parkar
  • 39
  • 2
  • 2
    The absolute difference? Or do you know that the timestamp you have is in the past? Also, did you try something, and how did it not work? – Benjamin W. Aug 16 '19 at 19:52

1 Answers1

1

To get the difference of the current time minus the provided timestamp (with GNU date and Bash 5.0 or newer), you could use the EPOCHSECONDS shell variable and the -d option of date:

$ echo $(((EPOCHSECONDS - $(date -d '08/16/2019 15:34:00' +%s)) / 60))
19

For Bash older than 5.0, you could use printf '%(%s)T' instead of EPOCHSECONDS:

echo $((($(printf '%(%s)T') - $(date -d '08/16/2019 15:34:00' +%s)) / 60))

And if you have a Bash older than 4.2 (or any POSIX shell), you have to use date twice:

echo $((($(date +%s) - $(date -d '08/16/2019 15:34:00' +%s)) / 60))

And if you don't have GNU date and its -d option, have a look at the Q&A at Parse Date in Bash: parse the date/time string with read, or use date's -jf flags on macOS.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116