鉴于时间的特殊性,您可以简单地使用Calendar
API
Calendar fromMidnight = Calendar.getInstance();
fromMidnight.set(Calendar.HOUR, 0);
fromMidnight.set(Calendar.MINUTE, 0);
fromMidnight.set(Calendar.SECOND, 0);
fromMidnight.set(Calendar.MILLISECOND, 0);
Calendar toMidnight = Calendar.getInstance();
toMidnight.setTime(fromMidnight.getTime());
toMidnight.add(Calendar.DATE, 1);
System.out.println(fromMidnight.getTime());
System.out.println(toMidnight.getTime());
Calendar toFromTime = Calendar.getInstance();
toFromTime.set(Calendar.HOUR, 8);
toFromTime.set(Calendar.MINUTE, 59);
toFromTime.set(Calendar.SECOND, 32);
toFromTime.set(Calendar.MILLISECOND, 0);
long secondsFromMidnight = (toFromTime.getTimeInMillis() - fromMidnight.getTimeInMillis()) / 1000;
long secondsToMidnight = (toMidnight.getTimeInMillis() - toFromTime.getTimeInMillis()) / 1000;
System.out.println("from = " + secondsFromMidnight + "; to " + secondsToMidnight);
哪个输出...
from = 32372; to 54028
或者你可以使用JodaTime ...
MutableDateTime now = MutableDateTime.now();
now.setMillisOfDay(0);
now.setSecondOfDay(32);
now.setMinuteOfDay(59);
now.setHourOfDay(8);
DateTime fromMidnight = now.toDateTime().toDateMidnight().toDateTime();
DateTime toMidnight = fromMidnight.plusDays(1);
Duration duration = new Duration(fromMidnight, toMidnight);
Duration dFromMidnight = new Duration(fromMidnight, now);
System.out.println("From midnight: " + dFromMidnight.getStandardSeconds());
Duration dToMidnight = new Duration(now, toMidnight);
System.out.println("To Midnight: " + dToMidnight.getStandardSeconds());
哪个输出...
From midnight: 32372
To Midnight: 54028