Loren
Loren

Reputation: 95

Check whether a timestamp is 1 hour old - Groovy

I have a timestamp (submitTime) which I need to check whether it is less than 1 hour old or not. Timestamps are in microseconds and including date.

currentTime = 1527530605357000000 (Monday, May 28, 2018 6:03:25.357 PM)

submitTime = 1527529918658907821 (Monday, May 28, 2018 5:51:58.659 PM)

        long currentTime = (long) (new Date().getTime()*1000000)
        submitTime = job.SubmitTime // part of the code
        oneHhour = 3600000000     

        if (currentTime - submitTime > oneHhour) {
            println job.Name + " env is up more than 1 hour";

But it doesn't work since the result is 686698092179 and it it not represent time. Help?

Upvotes: 0

Views: 1027

Answers (2)

Evgeny Smirnov
Evgeny Smirnov

Reputation: 3016

In groovy you can use TimeCategory which is much more intuitive:

def date = new Date(timestampInLong)

use (groovy.time.TimeCategory) {
     println (date > new Date() - 1.hour)
 }

Upvotes: 1

jspcal
jspcal

Reputation: 51924

Assuming SubmitTime is a timestamp in microseconds, you can compare it the the current timestamp in microseconds like so:

// Get the current time (System.currentTimeMillis) in microseconds:

long currentMicroseconds = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis())

// You could also simply do this:
long currentMicroseconds = System.currentTimeMillis() * 1000

// Subtract the timestamps and compare:

if (currentMicroseconds - job.SubmitTime > 3600000000) {
    // More than an hour has elapsed
}

The timestamp is assumed to be the number of microseconds since January 1, 1970, 00:00:00 GMT (consistent with Date.getTime).

Upvotes: 1

Related Questions