0

I am trying to compare two timestamps and if x is greater than y then do some action. I tried it with bash on my Linux machine but I get an error "invalid date" here is my code:

#!/bin/bash 
x='2020.01.23 14:41:18.554'
y='2020.01.23 17:17:02.323'

if [[ $(date -d "$x") -gt $(date -d "$y") ]]
 then
   echo -e "first value is greater than second"
       #### Perform some actions
       #### Perform some actions
  else
   echo "second value is greater, so do nothing"
fi
exit

when I run the script, I get below errors

date: invalid date `2020.01.23 14:41:18.554'
date: invalid date `2020.01.23 17:17:02.323'

I tried converting the whole value to epoch time and then compare, but in epoch time, milliseconds are not counted. How can get this comparison right including the milliseconds? Thank you.

0

There are two issues with your example.

First you need to replace the . in the calendar dates with either / or -. This gets rid of the invalid date error.

Then you need to add +%s%N to your date commands. This converts the date to epoch time in nanoseconds.

The following code works fine for me.

x='2020/01/23 14:41:18.554'    
y='2020/01/23 17:17:02.323'    

if [[ $(date -d "$x" +%s%N) -gt $(date -d "$y" +%s%N) ]]    
 then    
   echo -e "first value is greater than second"    
       #### Perform some actions    
       #### Perform some actions    
  else    
   echo "second value is greater, so do nothing"    
fi    
exit 

edit: see https://stackoverflow.com/questions/16548528/command-to-get-time-in-milliseconds for compatibility with nanoseconds

| improve this answer | |
0

Are all of your timestamps going to be of the form used in your example? If so, you can just compare them as strings.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.