Posted By

cruelfate on 01/07/11


Tagged

date Bash iso8601


Versions (?)

datediff.sh


 / Published in: Bash
 

Print difference between two ISO8601 formatted timestamps in seconds.

  1. #! /bin/bash
  2.  
  3. function usage {
  4. echo 'Subtract two timestamps in ISO 8601 format.'
  5. echo 'If end timestamp is missing, assume now.'
  6. echo 'Returns value in seconds.'
  7. echo ''
  8. echo 'usage: $0 start [end]'
  9. echo ''
  10. exit
  11. }
  12.  
  13. # ISO 8601 format is "yyyy-MM-dd'T'HH:mm:ssZ"
  14.  
  15. function iso8601_to_lbolt {
  16. u="$(echo $1 | sed -e 's/T/ /' | sed -e 's/-05:00/ EST/')"
  17. echo $(date -d "$u" +%s )
  18. }
  19.  
  20. if [ $# -lt 1 ] ; then
  21. usage
  22. fi
  23.  
  24. start=$(iso8601_to_lbolt $1)
  25.  
  26. if [ $# -eq 1 ] ; then
  27. end=$(date +%s)
  28. else
  29. end=$(iso8601_to_lbolt $2)
  30. fi
  31.  
  32. echo $(($end - $start))

Report this snippet  

You need to login to post a comment.