【问题标题】:Quick way to tell if current time is within 6 hours of midnight using JodaTime使用 JodaTime 快速判断当前时间是否在午夜后 6 小时内
【发布时间】:2012-02-24 15:56:33
【问题描述】:

所以我在我拥有的应用程序中使用 JodaTime,我需要一种方法来判断当前时间是否在午夜后 6 小时内。好吧,实际上我需要知道时间是否在凌晨 2 点的 8 小时内,但 JodaTime 似乎为午夜提供了一个常数,所以我正在查看。无论如何,我已经尝试了许多不同的东西,但没有什么能奏效。任何帮助或指点将不胜感激。

【问题讨论】:

    标签: java jodatime


    【解决方案1】:

    这可以通过使用 JodaTime 来完成,无需任何数学运算。

    DateTime time = new DateTime(DateTimeZone.UTC);
    
    Period period = new Period(time, time.plusDays(1).toDateMidnight());
    System.out.println(period.getHours());
    

    time.plusDays(1).toDateMidnight()(是的,我很懒惰),所以我要与下一个午夜进行比较,而不是与今天的午夜(已经过去)进行比较。

    如果你想同时检查之前和之后,只需检查两个时期。

    【讨论】:

      【解决方案2】:

      我建议使用 DateTime 对象。

      DateTime date = new DateTime();
      int i = getSecondOfDay();
      

      然后使用一点数学,我们可以找到下午 6 点的秒数。 18 小时*60 分钟*60 秒= 64800 秒。

      if ( i > 64800 ){
         // Do what you need here 
      }
      

      我假设您需要判断是当天上午 8 点,而不是特定日期。

      【讨论】:

        【解决方案3】:

        这有点硬编码,pcalcao 的答案可能更灵活:

        private static boolean isLessThan8HoursFrom2AM(DateTime date) {
            return (date.getHourOfDay() >= 18 || date.getHourOfDay() < 10);
        }
        

        【讨论】:

          【解决方案4】:

          您还可以检查一天中的时间是否距离中午 6 小时。

          if(Math.abs(timeOfDay - 43200) >= 21600) // first or last 6 hours of day.
          

          【讨论】:

            猜你喜欢
            • 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
            相关资源
            最近更新 更多