2012-09-16 145 views
0

我正在使用jxl api閱讀android中的excel文件。當我從excel中獲得「30/11/2012」的日期時,LabelCell輸出顯示日期爲「11/30/12」。獲取兩個日期之間的天數差異

1)我需要在讀取excel文件時以dd/MM/yyyy格式獲得輸出,因爲它在excel中以這種方式存在,所以我不想將其不必要地轉換爲另一種格式。怎麼做 ? 2)在閱讀excel專欄的日期後,我生成了2個變量,一個是excel日期--20天(讓我們稱之爲excelMinus20),另一個是excel日期+10天(讓我們稱之爲excelPlus10. )現在,我如果當前系統日期(智能手機的日期)> = excelMinus20和當前系統日期< = excelPlus10。

如何使用java.text.Date做到這一點?我嘗試使用joda時間作爲好吧,但它太複雜了,請引導我至少在正確的方向

在此先感謝 Omkar Ghaisas

回答

1

從文本格式解析您的日期:

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
Date date = formatter.parse("30/11/2012"); 

更多信息:SimpleDateFormat doc

從你的約會。減去天:

public static Date substractDays(Date date, int days) 
{ 
    long millis = date.getTime(); 
    long toSubstract = days * 1000 * 60 * 60 * 60 * 24; 
    //      1milli 1s 1m 1h 1d 
    return new Date(millis-toSubstract); 
} 

添加一些日子會是一樣的,除了替換 - 用+

取回String表示從Date對象離子:

DateFormat formatter = new SimpleDateFormat("...pattern..."); 
String formatedDate = formatter.format(date.getTime()); 

編輯:

你也可以做添加/你建議的方法從其減去日期:

public static Date substractDays(Date date, int days) 
{ 
    Calendar calendar = Calendar.getInstance(); 
    calendar.setTime(date); 
    calendar.add(Calendar.DATE, -20 /*or +10*/); 
    return calendar.getTime(); 
} 

如果你想檢查是否日期是在一個區間內,那麼:

public static boolean isInInterval(Date date, Date from, Date to) 
{ 
    return date.getTime()<to.getTime() && date.getTime() > from.getTime(); 
} 
+0

第二個問題就是說我想檢查我的當前系統日期是否在excelMinus20和excelPlus10日期之間,在這種情況下,我會根據業務邏輯採取適當的代碼操作。另外,我已經看到使用天* 1000 * 60 * 60 * 60 * 24;有時會給出不正確的結果,因此我使用了Calendar.add(Day_Of_Year,-20)來減去日期 - 20天。讓我知道,如果這很好。 –

+0

你好!我從來沒有任何手動計算毫秒的問題,但你可能是對的。如果是這樣,那麼看到我更新的答案。 –