Unix script to compare a timestamp with current time
The way your tools work depends on the flavour of Unix you use. The following should work in Linux, FreeBSD, NetBSD, OSX, etc.
#!/bin/shsample="${1:-20120306131701}"if ! expr "$sample" : '[0-9]\{14\}$' >/dev/null; then echo "ERROR: unknown date format" >&2 exit 65ficase $(uname -s) in *BSD|Darwin) # The BSD date command allows you to specify an input format. epoch=$(date -jf '%Y%m%d%H%M%S' "$sample" '+%s') ;; Linux) # No input format in Linux, so rewrite date to something '-d' will parse tmpdate="$(echo "$sample" | sed -r 's/(.{8})(..)(..)(..)/\1 \2:\3:\4/')" epoch=$(date -d "$tmpdate" '+%s') ;; *) echo "ERROR: I don't know how to do this in $(uname -s)." >&2 exit 69 ;;esacnow=$(date '+%s')# And with the provided datetime and current time as integers, it's MATH time.if [ $((now - epoch)) -gt 600 ]; then exit 1fiexit 0
Note that this is a /bin/sh
script, for the sake of portability, so it doesn't take advantage of bash-isms you may be used to in Linux, in particular [[ ... ]]
and heretext to read variables.
Oh, and I'm assuming that you meant "exit value" when you said "return value". A return value would be the result of a function, but what I've written above is a stand-alone script.
Note that this may not understand timestamps in the future, nor does it take timezone into consideration. If that's important to you, you should, er, consider it. :-) And test in your environment.
Assume $dbtimestamp has the timestamp returned from the database, but I'm hard-coding it here.
dbtimestamp=20120306142400secondsDiff=$(( `date '+%Y%m%d%H%M%S'` - $dbtimestamp ))if [ $secondsDiff -gt 600 ] then exit 1else exit 0fi