Skip to content

Instantly share code, notes, and snippets.

@snowindy
Created September 25, 2014 11:18
Show Gist options
  • Save snowindy/1f30babc59516bdc28ef to your computer and use it in GitHub Desktop.
Save snowindy/1f30babc59516bdc28ef to your computer and use it in GitHub Desktop.
public static int getSecondsToDayHour(Date fromDate, int hour) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
long seconds = (cal.getTime().getTime() - fromDate.getTime()) / 1000;
if (seconds < 0) {
cal.add(Calendar.DATE, 1);
seconds = (cal.getTime().getTime() - fromDate.getTime()) / 1000;
}
if (seconds > 24 * 60 * 60) {
throw new ProgramLogicException(String.format("Seconds result is incorrect: %s.", seconds));
}
return (int) seconds;
}
@Test
public void test_getSecondsToDayHour() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 22);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
assertEquals(12 * 60 * 60, DateUtils.getSecondsToDayHour(cal.getTime(), 10));
cal.set(Calendar.HOUR_OF_DAY, 7);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
assertEquals(3 * 60 * 60, DateUtils.getSecondsToDayHour(cal.getTime(), 10));
assertEquals(23 * 60 * 60, DateUtils.getSecondsToDayHour(cal.getTime(), 6));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment