Source From Here
Question
I print the start and end time using date +"%T", which results in something like:
How could I calculate and print the difference between these two? I would like to get something like:
How-To
I guess the easiest solution would be to obtain the time as the number of seconds since the Unix epoch, and then subtract them, doing the time arithmetic before displaying.
The -u parameter instructs date to return the time in UTC. This is needed in order to keep the timeline continuous : without that option, the calculation of diff could return an incorrect value if a DST transition happened between the two calls to date. This parameter is required by POSIX, so I bet it's widely supported across various Unices.
- test.sh
Execution result:
Question
I print the start and end time using date +"%T", which results in something like:
How could I calculate and print the difference between these two? I would like to get something like:
How-To
I guess the easiest solution would be to obtain the time as the number of seconds since the Unix epoch, and then subtract them, doing the time arithmetic before displaying.
The -u parameter instructs date to return the time in UTC. This is needed in order to keep the timeline continuous : without that option, the calculation of diff could return an incorrect value if a DST transition happened between the two calls to date. This parameter is required by POSIX, so I bet it's widely supported across various Unices.
- test.sh
- #!/bin/sh
- date1=$(date -u +"%s")
- sleep 5
- date2=$(date -u +"%s")
- diff=$(($date2-$date1))
- echo "$(($diff / 60)) minutes and $(($diff % 60)) seconds elapsed."
沒有留言:
張貼留言