2013-01-16 18 views
0

我需要幫助檢查下列有關日期和時間條件...如何檢查:dateOne <dateTwo

Calendar cal = Calendar.getInstance(); 
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); 

String CurrentDate= dateFormat.format(cal.getTime()); 

字符串ModifiedDate =日期時間日期從n個時間選擇器插件服用;

我要檢查:

當前ModifiedDate不不到5分鐘的當前時間

如何在安卓/ Java的檢查此conditon .......... ?

+0

這可以幫助你http://pankajchunchun.wordpress.com/2012/06/29/small-code-stuffs-used-for-validations-in-java -or-android /(檢查'檢查日期是未來的執行情況') –

+1

這不是關於'android' – Andremoniy

回答

1

你爲什麼格式化的日期?

使用「自然」表示而不是字符串表示形式處理數據要容易得多。目前尚不清楚您的修改日期是否將視爲一個字符串,但如果是這樣,您應該做的第一件事是解析它。然後,您可以比較當前日期和時間使用:

// Check if the value is later than "now" 
if (date.getTime() > System.currentTimeMillis()) 

// Check if the value is later than "now + 5 minutes" 
if (date.getTime() > System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5)) 

這不是真的清楚你的意思是「當前ModifiedDate是不是不到5分鐘當前時間。」 - 無論您的意思是不少於5分鐘之後,或不少於5分鐘之前,或者類似的事情 - 但您應該能夠更改上面的代碼來處理您的要求。

如果你做了很多的日期/時間操縱的,我強烈建議使用Joda Time,這比java.util.Date/Calendar一個更好的日期/時間API。

0

檢查給定時間是在當前時間之前還是之後, 在Android ...中有一個Calendar實例來比較日期時間值。

Calendar current_time = Calendar.getInstance(); 

current_time.add(Calendar.DAY_OF_YEAR, 0); 

current_time.set(Calendar.HOUR_OF_DAY, hrs); 

current_time.set(Calendar.MINUTE, mins); 

current_time.set(Calendar.SECOND, 0); 


Calendar given_time = Calendar.getInstance(); 

given_time.add(Calendar.DAY_OF_YEAR, 0); 

given_time.set(Calendar.HOUR_OF_DAY, hrs); 

given_time.set(Calendar.MINUTE, mins); 

given_time.set(Calendar.SECOND, 0); 


current_time.getTime(); 

given_time.getTime(); 


boolean v = current_calendar.after(given_calendar); 


// it will return true if current time is after given time 


if(v){ 

return true; 

} 
0
public static boolean getTimeDiff(Date dateOne, Date dateTwo) { 
    long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime()); 
    int day = (int) TimeUnit.MILLISECONDS.toHours(timeDiff); 
    int min= (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff))); 
    if(day>1) 
    { 
     return false; 
    } 
    else if(min>5) 
    { 
     return false; 
    } 
    else 
    { 
     return true; 
    } 
} 

用法:

System.out.println(getTimeDiff(new Date("01/13/2012 12:05:00"),new Date("01/12/2012 13:00:00"))); 
相關問題