15

I can do that in php with the following code:

$dt1 = '2011-11-11 11:11:11';
$t1 = strtotime($dt1);

$dt2 = date('Y-m-d H:00:00');
$t2 = strtotime($dt2);

$tDiff = $t2 - $t1;

$hDiff = round($tDiff/3600);

$hDiff will give me the result in hours.

How do I implement the above in bash shell?

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
denormalizer
  • 2,186
  • 3
  • 24
  • 36
  • This is pretty hard to do in most shell environments. I'd stick to a php script if that's what you're already comfortable with. Perl and Python are also good at this sort of thing. – bigendian Nov 14 '11 at 02:09

1 Answers1

39

You could use date command to achieve this. man date will provide you with more details. A bash script could be something on these lines (seems to work fine on Ubuntu 10.04 bash 4.1.5):

#!/bin/bash                                                                                                                                                   

# Date 1
dt1="2011-11-11 11:11:11"
# Compute the seconds since epoch for date 1
t1=$(date --date="$dt1" +%s)

# Date 2 : Current date
dt2=$(date +%Y-%m-%d\ %H:%M:%S)
# Compute the seconds since epoch for date 2
t2=$(date --date="$dt2" +%s)

# Compute the difference in dates in seconds
let "tDiff=$t2-$t1"
# Compute the approximate hour difference
let "hDiff=$tDiff/3600"

echo "Approx hour diff b/w $dt1 & $dt2 = $hDiff"

Hope this helps!

Socowi
  • 25,550
  • 3
  • 32
  • 54
another.anon.coward
  • 11,087
  • 1
  • 32
  • 38