我想知道如何找到自Java上次8:45以来已经过了多少时间。
离。
时间:8:44 - > 23:59
时间8:46 - > 00.01
我现在有一个相当难看的解决方案。
if (calendar.get(Calendar.HOUR_OF_DAY) >= 8) {
if (calendar.get(Calendar.MINUTE) >= 45 || calendar.get(Calendar.HOUR_OF_DAY) > 9) {
System.out.println("it between 8:45 and 00:00");
}
}
else {
System.out.println("its between 00:00 and 8:45");
}
答案 0 :(得分:0)
类似的东西:
public void test() {
Calendar c = Calendar.getInstance();
Calendar eightFortyFive = Calendar.getInstance();
eightFortyFive.set(Calendar.HOUR, 8);
eightFortyFive.set(Calendar.MINUTE, 45);
eightFortyFive.set(Calendar.SECOND, 0);
eightFortyFive.set(Calendar.MILLISECOND, 0);
// You might not need to do this or you may need to use -24.
if (eightFortyFive.after(c)) {
eightFortyFive.add(Calendar.HOUR, -12);
}
System.out.println("Time since " + eightFortyFive.getTime() + " = " + new Date(c.getTimeInMillis() - eightFortyFive.getTimeInMillis()));
}
基本上你必须花费当前时间,将小时,分钟,秒和毫秒设置为你想要的,并在必要时减去12或24小时。然后,您可以创建一个新的Date
,这是两者之间的差异。
答案 1 :(得分:0)
如果您只是希望到达日期之间的日子,可以使用以下内容:
public static void main(String[] args) {
long initial = getTime("20-jul-2015 11:09:25"); /*you use System.currentTimeMillis() at the beginning*/
long finalTime = getTime("21-jul-2016 15:21:26"); /*you use System.currentTimeMillis() at the capture of final time.*/
printElapsedTime(initial, finalTime);
}
private static void printElapsedTime(long initial, long finalTime) {
long lapse = finalTime - initial;
long secs = (lapse/(1000))%60;
long mins = lapse/(1000*60)%60;
long hrs = lapse/(1000*60*60)%24;
long days = lapse/(1000*60*60*24);
StringBuilder lapseMsg = new StringBuilder("Elapsed time since ").append(new Date(initial)).append(" to " + new Date(finalTime)).append(":\r\n");
lapseMsg.append(days).append(" Days, ").append(hrs).append(" Hours, ").append(mins).append(" Minutes, ").append(secs).append(" seconds");
System.out.println(lapseMsg.toString());
}
/*just used to get any date to test.*/
private static long getTime(String date) {
DateFormat format = DateFormat.getDateTimeInstance();
try {
return format.parse(date).getTime();
} catch (ParseException e) {
throw new RuntimeException();
}
}
如果您需要更复杂的内容,例如获取已失效的月份,您可以使用日历,对@OldCurmudgeon解决方案进行一些修复。 (它不像我那样对我有用)