Andro Selva
Andro Selva

Reputation: 54322

Compare hours and minutes

I am developing an app based on date and time in java. In this app, my user is allowed to record an video only once per hour. so for this I am storing the previous time has used my app.

So when the user starts my app for the next time, I am comparing the time and if the time interval is more than one hour I must allow my user to record, else I should not allow. How to compare hours and minutes efficiently in java?

Upvotes: 1

Views: 5240

Answers (4)

Prince John Wesley
Prince John Wesley

Reputation: 63698

From @Dalino answer, you may use TimeUnit enum class for time conversions.

long now = System.currentTimeMillis();
long lastVisit =  ...; // in milliseconds
if(TimeUnit.MILLISECONDS.toHours(now - lastVisit) > 0) {
    // allow
} 

Upvotes: 7

MarcoS
MarcoS

Reputation: 13564

I would use Joda Period: have a look here

Upvotes: 1

Danilo Tommasina
Danilo Tommasina

Reputation: 1760

Get the system time with

long time = System.currentTimeMillis();

and compare the new time with the old one. One hour means a difference of 1000 * 60 * 60 milliseconds

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1500695

Why not just store the time when they exit (or whatever) and then on start up, read the time, add an hour to it, and compare with the current time?

You don't need to compare the actual hours and minutes - just the duration of time between then and now.

Personally I'd suggest using Joda Time for all Java date/time work, but in this case you could just use Date, and add an hour's-worth of milliseconds. Note that you should definitely store a UTC date/time instead of a local one, as otherwise daylight saving changes etc will mess things up.

Upvotes: 2

Related Questions