2015-05-13 198 views
2

我想通過使用Calendar.getInstance().getTime()獲取當前時間並設置另一個2日曆變量來使用Calendar類。JAVA:如何檢查當前時間是否在指定時間

如何檢查,如果當前是2設定的時間之間,比使用getHourgetMinutes

+4

'日期#之後','日期#之前'和日期#等於... ...? – MadProgrammer

+0

MadProgrammer寫下的函數示例代碼位於:http://stackoverflow.com/questions/2309558/time-comparison – bish

+0

LocalDate和Period需要用於Java8。 –

回答

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"); 
} 
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."); 
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; 
} 

現在使用這個我thod:

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"); 
} 
相關問題