Reputation: 3653
I am setting up a date instance like this:
Calendar date = Calendar.getInstance();
date.set(2015, 9, 25, 12, 0);
In this case, I know that it's 12:00
, a full hour, but I also have cases where I input the date parameters dynamically, so I want to determine if that date is a full or half hour.
E.g., for 12:00
and 12:30
it would return true
, while for 12:23
it would return false.
I've tried timeInMillis % 36000000
from another answer, but it didn't work.
Upvotes: 1
Views: 2285
Reputation: 338835
You can let Java do the work for you. Use the java.time framework to query the date-time value for the minutes, seconds, and fraction-of-second.
ZonedDateTime now = ZonedDateTime.now ( ZoneId.of ( "America/Montreal" ) );
// If the value has any seconds or fraction of a second, we know this is neither full hour nor half hour.
if ( ( now.getSecond () != 0 ) || ( now.getNano () != 0 ) ) {
System.out.println ( "now: " + now + " is neither full nor half hour, because of seconds or fraction-of-second." );
return;
}
int minuteOfHour = now.getMinute ();
switch ( minuteOfHour ) {
case 0:
System.out.println ( "now: " + now + " is full hour." );
break;
case 30:
System.out.println ( "now: " + now + " is half hour." );
break;
default:
System.out.println ( "now: " + now + " is neither full nor half hour." );
break;
}
The java.util.Date/.Calendar classes bundled with the early versions of Java are notoriously troublesome, and should be avoided. The java.time framework supplants them.
Upvotes: 0
Reputation: 96
Use get minutes to check the minutes.
int minutes = date.get(Calendar.MINUTE); // gets the minutes
return (minutes == 0 || minutes == 30);
Upvotes: 4
Reputation: 1074555
You're on the right track, you've just used the wrong value. With milliseconds, it would be 1800000. (But see biziclop's comment suggesting that's not a good idea.) I'd get the minutes and use % 30 == 0
.
Gratuitous minutes example: (live copy)
for (int n = 0; n < 60; ++n) {
System.out.println(n + ( n % 30 == 0 ? " <= Yes" : ""));
}
Or in milliseconds: (live copy)
for (int n = 0; n < 3600000; n += 60000) {
System.out.println(n + ( n % 1800000 == 0 ? " <= Yes" : ""));
}
Upvotes: 2