Recently, when processing Shell scripts, I encountered time processing problems. Addition and subtraction of time, and calculation of time difference.
1. Time addition and subtraction
The processing method here is to convert the basic time into a timestamp, and then the time needs to be increased or changed to become seconds.
For example: 1990-01-01 01:01:01 plus 1 hour 20 minutes
Approach:
a. Convert base time to timestamp
time1=$(date +%s -d '1990-01-01 01:01:01')
echo $ time1
631126861 【Timestamp】
b. Turn the increase time into seconds
[root localhost ~]# time2=$((1*60*60+20*60))
[root localhost ~]# echo $time2
4800
c. Add the two times to calculate 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
Such as: 2010-01-01 and 2009-01-01 11:11:11 time difference
Principle: Also converted into timestamp, and then calculate days, hours, minutes, seconds
time1=$(($(date +%s -d '2010-01-01') - $(date +%s -d '2009-01-01 11:11:11')));
echo time1
After time1 / 60 seconds, it becomes a component.
Additional notes:
Shell single bracket operation symbol:
a=$(date);
Equivalent to: a = date;
Double bracket operator:
a=$((1+2));
echo $ a;
Equivalent to:
a=expr 1 + 2