Linux shell time calculation and time difference calculation method

  
 

Recently, when dealing with shell scripts, I encountered time processing issues. Addition and subtraction of time, and calculation of time difference.


1. Time addition and subtraction


The processing method here is to convert the base time into a timestamp, and then, it is necessary to increase or change the time to become seconds.


如:1990-01-01 01:01:01 plus 1 hour 20 minutes

Processing method:

a.Basic time Convert to timestamp

time1=$(date +%s -d '1990-01-01 01:01:01')

echo $time1

631126861 Timestamp]


b. Increase the time to seconds

[root@localhost ~]# time2=$((1*60*60+20*60 ))[root@localhost ~]# echo $time2

4800


c. Adding two times and calculating the result time

time1 =$(($time1+$time2))

time1=$(date +%Y-%m-%d\\ %H:%M:%S -d "1970-01-01 UTC $ Time1 seconds");

echo $time1

1990-01-01 02:21:01


2. Time difference calculation method


For example: 2010-01-01 and 2009-01-01 11:11:11 Time difference

Principle: Also convert to timestamp, then calculate Day, hour, minute, second


time1=$(($(date +%s -d '2010-01-01') - $(date +%s -d ' 2009-01-01 11:11:11')));

echo time1


The time1 /60 seconds will change.


Additional Note:

shell Single Bracket Operator Symbol:

a=$(date);

Equivalent to: a =`date`;


Double bracket operator:

a=$((1+2));

echo $a;< Br>

is equivalent to:

a=`expr 1 + 2`

Copyright © Windows knowledge All Rights Reserved