【问题标题】:How much time has passed since the last time it was "X" a clock自上次时钟为“X”以来已经过去了多少时间
【发布时间】:2015-07-20 15:13:56
【问题描述】:

我想知道如何找到自上次在 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");
}

【问题讨论】:

  • 使用 Period 更容易(在 java 1.8 上可用)-link
  • 我们说的是一天 24 小时吗?或者您是否需要考虑daylight saving time 转换造成的缺失时间间隔和重复时间重叠?

标签: java time


【解决方案1】:

类似:

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,这是两者之间的区别。

【讨论】:

  • 您需要减去 24 小时 - OP 很清楚他正在处理 24 小时制。
  • @dcsohl - 我不确定我是否真的需要减法。
【解决方案2】:

如果您只想了解日期之间的天数,可以使用以下内容:

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 解决方案进行一些修复。 (它对我不起作用)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多