How to add n hours to a specified time?
I'd like to have a time, say 6:45am, and add an amount of hours, say 1.45 hours, to result in another time. So I'd like to add 1.45 hours to 6:45am to get another time.
Is there a command line utile for that? I've done some Googling, and read the man page for date
and haven't found anything like that. wcalc
doesn't seem to handle time calculations.
EDIT: Mar 6, 2015. This is the script I ended up with to use decimal hours. It could use some error checking to make sure HH:MM uses 2 digits for the hours.
#!/bin/bash
# Mar 6, 2015
# Add decimal hours to given time.
# Syntax: timeadd HH:MM HOURS
# There MUST be 2 digits for the hours in HH:MM.
# Times must be in military time.
# Ex: timeadd 05:51 4.51
# Ex: timeadd 14:12 2.05
echo " "
# If we have less than 2 parameters, show instructions and exit.
if [ $# -lt 2 ]
then
echo "Usage: timeadd HH:MM DECHOURS"
exit 1
fi
intime=$1
inhours=$2
# Below is arithmetic expansion $(())
# The bc calculator is standard on Ubuntu.
# Below rounds to the minute.
inminutes=$(echo "scale=0; ((($inhours * 60)*10)+5)/10" | bc)
echo "inminutes=$inminutes"
now=$(date -d "$intime today + $inminutes minutes" +'%H:%M')
echo "New time is $now"
Command line:
$ now=$(date -d "06:45 today + 105 minutes" +'%H:%M')
$ echo "$now"
08:30
$now
will hold the time you specified.
You can put a lot of things in between the " and "; like the current time and add 105 to it.
$now=$(date -d "06:45 today + 2.5 hour" +'%H:%M')
date: invalid date `06:45 today + 2.5 hour'
$now=$(date -d "06:45 today + 2:30 hour" +'%H:%M')
date: invalid date `06:45 today + 2:30 hour'
$ now=$(date -d "06:45 today + 2 hour" +'%H:%M')
$ echo "$now"
08:45
No decimals allowed...
From comments: To get the answer for 1.45 decimal hours:
$ now=$(date -d "06:45 today + $((145 * 60 / 100)) minutes" +'%H:%M')
$ echo "$now:
8:12