Home > Software engineering >  Calculate earlier and later times, then compare with a given time
Calculate earlier and later times, then compare with a given time

Time:10-26

I need to calculate if a certain time is between 30 minutes earlier and 20 minutes later than the current time.

Any idea how to do this?

The problem is when the time is 23:50h, for example. So I can't do a simple comparison since 23 is greater than 00. But I must consider it smaller since it's another day.

Example:

Now is 23:45.

23:45 - 30 minutes = 23:15.

23:45 20 minutes = 00:05.

Is 23:50 between 23:15 and 00:05?

minSdkVersion is 22, and this further limits the available solutions.

Extra:

In javascript, I would solve it this way:

var early = new Date(); // 23:45
var later = new Date(); // 23:45
var comparison = new Date(); // 23:45

comparison.setHours(23);
comparison.setMinutes(50);

early.setMinutes(early.getMinutes() - 30);
later.setMinutes(later.getMinutes()   20);

console.log((early <= comparison) && (later >= comparison));

CodePudding user response:

The easiest way to go is :

Compare Hours separately from minutes.

Or also you can take the Hours, multiply them for 60 and then add the returning value to the minutes amount, that will end up with a "only minute" calculation between the 2 times. You can make whatever operation you need.

The only case you should calculate is that one you are in a different day, but that dipends and what you are trying to accomplish!

CodePudding user response:

The easiest way is just to work with timestamps.

long time = new Date().getTime();
long thiry_earlier = time - minutes_to_ms(30);
long twenty_later = time   minutes_to_ms(20);

if(compare < twenty_later && compare > thirty_earlier) {
//do whatever
}

long minutes_to_ms(long minutes) {
  return minutes*60*1000;
}

There's some nicer conversion functions you can use nowdays I'm just too lazy to look them up. But working with raw timestamps makes everything easier for comparisons.

  • Related