Created
September 25, 2014 11:18
-
-
Save snowindy/1f30babc59516bdc28ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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