Friday, June 14, 2013

Calculate time difference using bash script

This can be done easily if you convert your time string into epoch which is the number of seconds since 1st January 1970. Before you can do it, make sure the time string you want to convert is in correct format. One of the accepted format is "yyyy/mm/dd hh:mm:ss". In my case, the time string format is actually "yy/mm/dd/hh:mm:ss", but with little tweak by appending 20 to my time string, i can get the accepted format.

So to do that you need to use date command with -d option (display time described by STRING) and +%s format control (epoch).

Example:
currDate="2013/05/30 18:18:20"
prevDate="2013/05/30 18:18:10"
currDateEpoch=`date -d "$currDate" +%s`
prevDateEpoch=`date -d "$prevDate" +%s`
delta=$(($currDateEpoch-$prevDateEpoch))

And the delta result is 10 seconds.

No comments: