【问题标题】:Java. Check time range. How?爪哇。检查时间范围。如何?
【发布时间】:2011-11-21 16:08:58
【问题描述】:

例如,我有输入参数这种格式:“04:00-06:00”或“23:00-24:00”。参数类型 - String

在我的方法中,我必须检查输入参数中的时间范围不在当前时间之前。我该怎么做?

更多细节:

输入时间范围:“12:00-15:00

当前时间:16:00

在这种情况下,方法必须返回false

另一个例子:

输入时间范围:“10:30-12:10

当前时间:09:51

方法必须返回true

你能给我一些想法或算法吗?我该如何实现这个方法?

【问题讨论】:

  • 这应该标记为作业吗?
  • 没有。这不是家庭作业。你错了。

标签: java date time date-range


【解决方案1】:
Date currentDate = new Date();
Date maxDate;
Date minDate;

//Parse range to two substrings
//parse two substrings to [HH, MM]
//for HH && MM parseInt()
//
minDate= new Date.SetHour(HH); minDate.SetMinute(MM);
//repeat for max date

if(currentDate.Before(maxDate) && currentDate.After(minDate))
{
return true;
}
else
return false;

【讨论】:

  • setHours 和 setMinute 是已弃用的方法。
  • 抱歉,我在阅读旧文档时使用了 Calendar 类中的等效方法。例如maxDate = 新日历(); maxDate.set(HOUR,HH); currentDate.after(maxDate);
【解决方案2】:

首先,你可能应该学会使用Joda time

也就是说,由于时间都是用零填充的,所以您可以按词法比较字符串。

public static boolean inRange(String time, String range) {
  return time.compareTo(range.substring(0, 5)) >= 0
      && time.compareTo(range.substring(6)) <= 0;
}

在格式错误的输入上快速失败是一个好习惯。

private static final Pattern VALID_TIME = Pattern.compile("[012][0-9]:[0-5][0-9]");
private static final Pattern VALID_RANGE = Pattern.compile("[012][0-9]:[0-5][0-9]-[012][0-9]:[0-5][0-9]");

然后在inRange的顶部放置一个断言:

assert VALID_TIME.matcher(time).matches() : time
assert VALID_RANGE.matcher(range).matches() : range

编辑:

如果你真的需要将当前时间表示为Date,那么你应该这样比较:

 public final class Range {
   /** Inclusive as minutes since midnight */
   public final int start, end;
   public Range(int start, int end) {
     assert end >= start;
   }

   /** @param time in minutes since midnight */
   public boolean contains(int time) {
     return start <= time && time <= end;
   }

   public static Range valueOf(String s) {
     assert VALID_RANGE.matcher(s).matches() : s;
     return new Range(minutesInDay(s.substring(0, 5)),
                      minutesInDay(s.substring(6));
   }

   private static int minutesInDay(String time) {
     return Integer.valueOf(time.substring(0, 2)) * 60
         + Integer.valueOf(time.substring(3));
   }
 }

使用Range.valueOfString 转换,将Date 转换为您喜欢的任何时区午夜后的分钟数,使用您喜欢的任何日历实现,然后使用Range.contains

【讨论】:

  • 当前时间是日期而不是字符串。
  • 我同意你的看法。这是一个很好的解决方案......但我不能使用任何库。只有标准功能和标准包。
  • @user471011,为什么你不能使用图书馆?什么是“标准功能”?上面的Range 类不适合你吗?
猜你喜欢
  • 1970-01-01
  • 2013-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多