Bash script: difference in minutes between two times
A pure bash solution :
old=09:11
new=17:22
# feeding variables by using read and splitting with IFS
IFS=: read old_hour old_min <<< "$old"
IFS=: read hour min <<< "$new"
# convert hours to minutes
# the 10# is there to avoid errors with leading zeros
# by telling bash that we use base 10
total_old_minutes=$((10#$old_hour*60 + 10#$old_min))
total_minutes=$((10#$hour*60 + 10#$min))
echo "the difference is $((total_minutes - total_old_minutes)) minutes"
Another solution using date
(we work with hour/minutes, so the date is not important)
old=09:11
new=17:22
IFS=: read old_hour old_min <<< "$old"
IFS=: read hour min <<< "$new"
# convert the date "1970-01-01 hour:min:00" in seconds from Unix EPOCH time
sec_old=$(date -d "1970-01-01 $old_hour:$old_min:00" +%s)
sec_new=$(date -d "1970-01-01 $hour:$min:00" +%s)
echo "the difference is $(( (sec_new - sec_old) / 60)) minutes"
See http://en.wikipedia.org/wiki/Unix_time
How to calculate time elapsed in bash script?
Bash has a handy SECONDS
builtin variable that tracks the number of seconds that have passed since the shell was started. This variable retains its properties when assigned to, and the value returned after the assignment is the number of seconds since the assignment plus the assigned value.
Thus, you can just set SECONDS
to 0 before starting the timed event, simply read SECONDS
after the event, and do the time arithmetic before displaying.
#!/usr/bin/env bash
SECONDS=0
# do some work
duration=$SECONDS
echo "$(($duration / 60)) minutes and $(($duration % 60)) seconds elapsed."
As this solution doesn't depend on date +%s
(which is a GNU extension), it's portable to all systems supported by Bash.
Shell: How to compare two Time strings and return difference in minutes?
Convert your times to epoch and calculate seconds. I assume that you don't get your times from date
because if so you can just format with "+%s"
to get the epoch time immediately. The answer assumes you just have two strings with %H%M
.
So, assign your strings with the timestamp (hour and minute)
current_utc_time=$(date +"%H%M")
sch_time=$(date +"18%M")
Convert to unix timestamp.
macOS
epoch_current=$(date -j -f "%H%M" "$current_utc_time" +%s)
epoch_sch=$(date -j -f "%H%M" "$sch_time" +%s)
Linux
epoch_current=$(date --date "$current_utc_time" +%s)
epoch_sch=$(date --date "$sch_time" +%s)
Calculate your diff (in minutes).
diff_in_minutes=$(( ($epoch_sch - $epoch_current) / 60 ))
how to calculate the total minutes between two dates?
echo $((($(date -ud "$date2" +'%s') - $(date -ud "$date1" +'%s'))/60)) minutes
Calculate the difference between two timestamps in bash
What about this?
#!/usr/bin/env bash
echo "BASH_VERSION:" $BASH_VERSION
line="2020-05-21 05:52:47;2020-05-28 19:37:36"
IFS=';' read -a dates <<< $line
startDatetime=${dates[0]}
endDatetime=${dates[1]}
echo "| dates -> " ${dates[@]}
echo "|> startDatetime -> ${startDatetime}"
echo "|> endDatetime -> ${endDatetime}"
startTime=$(date -jf "%Y-%m-%d %H:%M:%S" "${startDatetime}" +%s)
endTime=$(date -jf "%Y-%m-%d %H:%M:%S" "${endDatetime}" +%s)
diffSeconds="$(($endTime-$startTime))"
echo "Diff in seconds: $diffSeconds"
# at this point you have the diff in seconds and you can parse it however you want :)
diffTime=$(gdate -d@${diffSeconds} -u +%H:%M:%S) # you'll need `brew install coreutils`
echo "Diff time(H:M:S): $diffTime"
Output:
BASH_VERSION: 5.0.17(1)-release
| dates -> 2020-05-21 05:52:47 2020-05-28 19:37:36
|> startDatetime -> 2020-05-21 05:52:47
|> endDatetime -> 2020-05-28 19:37:36
Diff in seconds: 654289
Diff time(H:M:S): 13:44:49
To install the latest bash
I found this medium post.
Note: If this doesn't work because some version incompatibilities with the date
function, for example, the idea should be pretty similar and you could find a workaround that adapts to your current version, I'm sure. Logically, the easiest solution I see is:
1st) Split the string into two: one for each DateTimes.
2nd) Transform each DateTime from string to dates.
3rd) Apply a diff between these dates: using the seconds from each.
4th) Having the diff seconds you can display it as you want (year, days, minutes, seconds)
Bash script to calculate time difference
I guess you are just having difficulties to formulate the loop in bash syntax. Here you go:
#!/bin/bash
START_TIME=10:46:20
TIME_Record=(
11:03:00
11:24:00
11:27:00
11:32:00
)
SEC1=$(date +%s -d "${START_TIME}")
for d in "${TIME_Record[@]}"
do
SEC2=$(date +%s -d "$d")
DIFFSEC=$(( SEC2 - SEC1 ))
echo "$DIFFSEC"
done
Calculate the time difference in minutes between two time values
You should calculate the time difference first, then do the logic. That way you can always show the difference regardless of the outcome of the test. To do the difference, convert to some common base like seconds or minutes, then format however suits for presentation, e.g.
function getTimeDiff(h1, m1, s1, h2, m2, s2) {
return diff = toSeconds(h2, m2, s2) - toSeconds(h1, m1, s1);
}
function toSeconds(h, m, s) {
return h*3600 + m*60 + s*1;
}
function secondsToHMS(secs) {
function z(n){return (n<10? '0':'') + n}
return z(secs/3600|0) + ':' +
z((secs%3600)/60|0) + ':' +
secs%60;
}
// Tests
[[4,23,15, 5,5,8], // 04:23:15 vs 05:05:08
[4,23,15, 4,25,8]]. // 04:23:15 vs 04:25:08
forEach(function(arr) {
var diff = getTimeDiff(...arr);
console.log(`Diff of ${secondsToHMS(diff)} is ${diff > 600? 'more':'less'} than 10 minutes`);
});
Related Topics
How to Know Which Device Is Connected in Which /Dev/Ttyusb Port
Command to Insert Lines Before First Match
How to Keep Executable Code in Memory Even Under Memory Pressure? in Linux
Undefined Reference to Symbol 'Dlsym@@Glibc_2.4'
Bumping Version Numbers for New Releases in Associated Files (Documentation)
Checkpoint/Restart Using Core Dump in Linux
How to Read Data from Excel Sheet in Linux Using Shell Script
How to Use Cx_Freeze in Linux to Create a Package to Be Used in Windows
Command for Finding Process Using Too Much Cpu
Cannot Clone Repository: Fatal: R Any Gitolite-Admin Gitolite Denied by Fallthru
Is a Core Dump Executable by Itself
How to Overcome an Incompatibility Between the Ksh on Linux VS. That Installed on Aix/Solaris/Hpux
How to Use Watir to Scrape Data from a Website on a Linux Server Without Monitor
How to Use Sed to Change File Extensions