JAVA:如何检查当前时间是否在指定时间之间

时间:2015-05-13 04:58:20

标签: java

我想通过使用Calendar.getInstance().getTime()来获取当前时间并设置另一个2 Calendar变量来使用Calendar类。

除了使用getHourgetMinutes

进行比较之外,我如何检查当前是否在2个设定时间之间

3 个答案:

答案 0 :(得分:0)

试试这样:

String str1= "21:19:17";
Date t1 = new SimpleDateFormat("HH:mm:ss").parse(str1);
Calendar c1 = Calendar.getInstance();
c1.setTime(t1 );

String str2 = "12:32:00";
Date t2 = new SimpleDateFormat("HH:mm:ss").parse(str2);
Calendar c2= Calendar.getInstance();
c2.setTime(t2);
c2.add(Calendar.DATE, 1);

String currenttime = "02:13:47";
Date d = new SimpleDateFormat("HH:mm:ss").parse(currenttime);
Calendar c3 = Calendar.getInstance();
c3.setTime(d);
c3.add(Calendar.DATE, 1);

Date x = c3.getTime();
if (x.after(c1.getTime()) && x.before(c2.getTime()))
{
    System.out.println("Yes it is in the range");
}

答案 1 :(得分:0)

    String timeFrom = "12:00:00";
    String timeTo = "15:00:00";
    String timePoint="14:30:20";

    Long timeFromVal = Time.parse(timeFrom);
    Long timeToVal = Time.parse(timeTo);
    Long timePointVal = Time.parse(timePoint);

    if(timePointVal>timeFromVal && timePointVal<timeToVal)            
            Log.i("Time report ","Time is Valid.");

答案 2 :(得分:0)

首先创建一个可重复使用的方法来设置日历时间:

private Calendar setTimeToCalendar(String dateFormat, String date, boolean addADay) throws ParseException {
    Date time = new SimpleDateFormat(dateFormat).parse(date);
    Calendar cal = Calendar.getInstance();
    cal.setTime(time );

    if(addADay) {
        cal.add(Calendar.DATE, 1);
    }
    return cal;
}

现在使用此方法:

String dateFormat = "HH:mm:ss";
String startTime= "20:20:20";
String endTime= "12:12:12";
String currentTime = new SimpleDateFormat(dateFormat).format(new Date());

Calendar cStart = setTimeToCalendar(dateFormat, startTime, false);
Calendar cEnd = setTimeToCalendar(dateFormat, endTime, true);
Calendar cNow = setTimeToCalendar(dateFormat, currentTime, true);   
Date curDate = cNow.getTime();

if (curDate.after(cStart.getTime()) && curDate.before(cEnd.getTime())) {
    System.out.println("Date is in range");
} else {
    System.out.println("Date is out of range");
}