Java检查给定的小时和分钟是否位于两个日期之间。小时和分钟

时间:2014-10-15 05:59:20

标签: java android jodatime

我有时间跨度:

long dateStart = System.currentTimeMillis();
long dateEnd = System.currentTimeMillis() + 60*60*1000;

我想检查mHourmMinutedateStart之间是否dateEnd.mHour = 11

例如,mMinute = 22dateStart < 11:22 < dateEnd,我想要的是2014/10/25 15:46 < 10:30 < 2014/10/26 : 15:45, the expected result will be true. Because, 2014/10/26 10:30 < 2014/10/26 : 15:45

这里的日期并不重要。

另一个例子:

the lower and upper bounds of dateStart and dateEnd cannot exceed 1 day span. So, if dateStart is 
2014/10/26 23:59, the most dateEnd would be 2014/10/27 23:58.

澄清:

 compareTime(dateStart ,dateEnd ,mHour  ,mMinute );



 public static void compareTime(long time1, long time2, int mHour, int mMinute) throws ParseException {

    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(new Date(time2));

    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(new Date(time1));
    calendar2.add(Calendar.DATE, 1);

    String someRandomTime = selectedHour + ":" + selectedminute;
    Date d = new SimpleDateFormat("HH:mm").parse(someRandomTime);
    Calendar calendar3 = Calendar.getInstance();
    calendar3.setTime(d);
    calendar3.add(Calendar.DATE, 1);

    Date x = calendar3.getTime();

    if (x.after(calendar1.getTime()) && x.before(calendar2.getTime()))
        System.out.println(true);

}

我做到了这一点,但没有成功:

{{1}}

1 个答案:

答案 0 :(得分:1)

这只是与Joda-time库有关。 compareTime方法如下:

   /**
    * @param time1 dateFrom in millis. E.g. returned by System.currentTimeMillis()
    * @param time2 dateTo in millis
    * @param mHour hours in your time zone
    * @param mMinute minutes in your time zone
    */
   public static boolean compareTime(long time1, long time2, int mHour, int mMinute)  
   {
      final LocalTime timeFrom = new LocalTime(time1);
      final LocalTime timeTo = new LocalTime(time2);
      final LocalTime time = new LocalTime(mHour, mMinute);
      final boolean isSameDay = timeFrom.isBefore(timeTo); // it is correct, because (time2 - time1 < 24 hours)
      return isSameDay ? (time.isAfter(timeFrom) && time.isBefore(timeTo))
         :  (time.isAfter(timeFrom) || time.isBefore(timeTo));
   }