Difference in seconds between user input and current date - bash

I need difference between two dates in seconds. I input datetime in format "YYYY-MM-DD HH:MM" and then calculate difference in seconds, but the run_time is in UTC timezone and current_time is calculated from system timezone.
#!/bin/bash
run_time=$1
run_time=$(date -d "$run_time" +"%s")
current_time="$(date +"%s")"
echo $run_time
echo $current_time
echo "$(($run_time-$current_time))"
How to retrieve absolute value of seconds between current datetime and another one?
Edit: actually that script has worked after restart of computer. No clue why previously it showed up different results. I have not changed anything in settings, nor computer time.

Right #Jetchisel, based on your comment a sample script could look like:
#!/bin/bash
STARTTIME_UTC=$1
STARTTIME_UTC=$(date -u -d "${STARTTIME_UTC}" +"%s")
echo "CURRENT DATE: $(date)"
CURRENTTIME="$(date +"%s")"
echo
echo "STARTTIME_UTC: ${STARTTIME_UTC} sec since"
echo "CURRENTIME: ${CURRENTTIME} sec since"
echo
echo "RUNTIME: $((${CURRENTTIME}-${STARTTIME_UTC})) sec"
As per original question
I input datetime in format "YYYY-MM-DD HH:MM"
the value of input time seconds in ${STARTTIME_UTC} will be set to zero (:00) whereby the value of current time seconds in ${CURRENTIME} will be set to what the clock provides. I.e., if it is 18 seconds before the next minute and the runtime would be almost zero, the script will report a difference of 42 seconds.

Related

Calculate number of days between 2 dates Unix Shell

I want to calculate number of days between two dates in the unix shell .
I tried to do a minus calculation but it dosen’t work .
This is my script
VAR1=$1
VAR2=$2
v_date_deb=`echo ${VAR1#*=}`
v_date_fin=`echo ${VAR2#*=}`
dif = ($v_date_deb - $v_date_fin)
echo dif
if [ "$v_date_deb" = "" ]
then
echo "Il faut saisir la date debut.."
exit
fi
if [ "$v_date_fin" = "" ]
then
echo "Il faut saisir la date fin.."
exit
fi
One attempt (but shot in the dark, since we don't know what is in your VAR1 variables)
ts1=$(date -d "${VAR1#*=}" +"%s")
ts2=$(date -d "${VAR2#*=}" +"%s")
dt=$(( (ts2 - ts1) / 86400 ))
Note the remark from William Pursell above: this solution is dependent on your "date" version. Date is not a built-in command from bash. And, particularly, the -d option (that allows to use the date specified instead of the current date that date is supposed to use otherwise, when used in "print the date" mode) is not common to all "date".

Bash - Calculating the time until zero for a queue

I am trying to write a simple script that helps me estimate the time left in an entry queue. So far I have gotten this, but it seems to deliver entirely random results, especially as the time in queue gets longer, or the position gets closer to zero.
To clarify, the script prompts for the initial position 'inum' whenever the queue moves, the user is prompted to enter the current place in queue. (There is no constant movement) I wanted to calculate the time until entry by taking the current place in queue, comparing it to the total amount of people, and then use the elapsed time in queue as a means to estimate a remaining time (+ a 5 Minute grace period). However, this gives me very inconsistent results.
#!/bin/sh
read -p "Users in queue: " inum;
echo ""
n=$inum
t0=$(date +%s)
while true; do
read -p "Users in queue: " nleft;
t=$(date +%s)
d=$((t - t0))
cal=$(echo "((($d * $nleft / ($n - $nleft)) - $d) / 60) + 5" | bc)
echo "Time in queue: $((d / 60)) Minutes."
echo "Approximate time left: $cal Minutes."
echo ""
done
echo "End."
with time command, use
time yourscript.sh
or with
start=`date +%s`
read -p "Users in queue: " nleft; #into while
end=`date +%s`
caltime=$( echo "$end - $start" | bc -l )

Difference between times using date function MACOSX

Calculate duration in HH:MM:SS format using difference in start and end time.
# Time Arithmetic
TIME1="00:30:20"
TIME2="00:30:50"
# Convert the times to seconds from the Epoch
SEC1=`date -j -f '%T' $TIME1 "+%s"`
#echo $SEC1
SEC2=`date -j -f '%T' $TIME2 "+%s"`
#echo $SEC2
# Use expr to do the math, let's say TIME1 was the start and TIME2 was the finish
DIFFSEC=`expr ${SEC2} - ${SEC1}`
#echo $DIFFSEC
echo Start ${TIME1}
echo Finish ${TIME2}
echo Took ${DIFFSEC} seconds.
# And use date to convert the seconds back to something more meaningful
result=`date -r $DIFFSEC "+%T"`
echo Result ${result}
Expected : Result 00:30:30 00:00:30(corrected)
Actual : Result 05:30:30
EDIT Actual TIME1 and TIME2 will be coming as params, and intension here is not to calculate time elapsed. It is a sample code i have used to demonstrate the issue. Strangely when TIME1=05:30:20 and TIME2=05:30:50 then also Result is : 05:30:30
Corrected Subject.
I finally settled with below, thanks anyways.
result=$(printf '%02d:%02d:%02d' $(($DIFFSEC/3600)) $(($DIFFSEC%3600/60)) $(($DIFFSEC%60)))

Error in bash time comparison

I have a bash script that creates a file with a timestamp as the name. Once some time passes, it is supposed to pick up that file and do something with it. I want it to pick it up after two hours, but for some reason, it is picking it up after 57 minutes (and 6 seconds). Can anyone point me to an error in my logic or assumptions?
Here are the details:
I have a variable set to 2 hours (7200 seconds):
SERVICE_DURATION=${SERVICE_DURATION:-7200} # seconds
I am setting the filename equal to the Unix timestamp concatenated with nanoseconds:
active_name=`date +%s%N`
echo "${1}" >> ${ACTIVE_DIR}/${active_name}
I then loop forever until the time is right:
while true
do
for fa in ${ACTIVE_DIR}/*
do
if [ $(basename ${fa}) -le $(($(date +%s%N) - ${SERVICE_DURATION} * 1000000000)) ]
then
exec 6< "${fa}"
read old_port <&6
read old_host <&6
read old_config <&6
exec 6<&-
logger -p daemon.info "Recycling port ${old_port}."
start_remote_service "${old_port}"
stop_remote_service "${old_port}" "${old_host}" "${old_config}" "${fa}"
sleep 2
fi
done
sleep 30
done
I can't see what is wrong with this. The filename ($(basename ${fa})) shouldn't be less than the current time minus the specified duration in nanoseconds ($(($(date +%s%N) - ${SERVICE_DURATION} * 1000000000))) until the duration has passed.
In order to keep the script from constantly checking, there is a sleep 30 at the end of the loop, so it could be that the time is somewhere between 56:36 and 57:06.
Any help would be appreciated. Thanks.

Arithmetic operation on time variable in c-shell

I need help using time in the c-shell
I want to know how much time it took to execute a script,so i want to do in the following way
1.set start_time=time
2 script part
3.set end_time=time
4. set diff=end_time-start_time
5.echo "It took $diff seconds"
but i couldn't get the time value using any command.
could any one suggest a command to read the time value in c-shell
I think you want the "date" command, with the format to give you raw seconds:
# start_time = `date +%s`
script part
# end_time = `date +%s`
# diff = $end_time - $start_time
echo "It took $diff seconds"

Resources