Alex
Alex

Reputation: 2805

Comparing epoch dates in different formats for a specific time gap

Capturing the last built date from Jenkins gives me an epoch date in the format 1493146210998, whereas today's date is (roughly, at the time of writing) 1493146250. Obviously they're in different units.

I need to check the two dates, and find out if "right now" is at least eight hours later than the jenkins timestamp. I think I'm correctly converting the first timestamp to match the units of the second (diving by 1000) but the math involved in comparing the two is tripping me up.

This will be in a bash script and will end up something like;

jenkinsBuild="1493146210998"
lastBuild=(`expr $jenkinsBuild / 1000`)
currentTime=(`date +%s`)

if( "$lastBuild" is less than eight hours before "$currentTime" ) {
        echo "Times are too close together."
    }

How do I check if the two times are less than eight hours apart? Feel free to substitute today's date if this gets answered more than eight hours from now.

Upvotes: 0

Views: 480

Answers (2)

Inian
Inian

Reputation: 85790

You can use the bash arithmetic operator $((..)) in an if-clause as

jenkinsBuild="1493146210998"
if (( $(( ($(date +%s) - $(date -d@${jenkinsBuild:0:10} +%s))/(60*60) )) < 8 )); then
    echo "Times are too close together."
fi

The idea is to get the 10 digits from the jenkinsBuild variable and do the GNU date arithmetic to get the EPOCH value in hours and see if it is less then 8 to get the condition working.


Seems OP has the native Mac OS X version of bash, which does not have GNU toolkit and no GNU date command, so do the arithmetic as

jenkinsBuild="1493146210998"
if (( $(( ($(date +%s) - ${jenkinsBuild:0:10} )/(60*60) )) < 8 )); then
    echo "Times are too close together."
fi

Upvotes: 1

clt60
clt60

Reputation: 63952

In bash v4.4+ you can use pure bash, like:

jenkinsBuild="1493146210998"
diff=$(( $(printf "%(%s)T") - (jenkinsBuild/1000) ))

(( diff < 8*60*60 )) && echo "Too close" || echo "OK"

#or    
if (( diff < 8*60*60 )); then
        echo "Too close"
else
        echo OK
fi

Upvotes: 0

Related Questions