2011-10-07 114 views
2

我得到今天的日期是這樣的:Android:前幾天如何計算日期?

final Calendar cal = Calendar.getInstance(); 
{ 
    mYear = cal.get(Calendar.YEAR); 
    mMonth = cal.get(Calendar.MONTH); 
    mDay = cal.get(Calendar.DAY_OF_MONTH); 
} 

我想計算究竟是什麼日期X天前...任何人得到的東西?

+0

不是真的一樣的問題.. –

+0

查看答案http://stackoverflow.com/a/27728430/1318946 –

回答

2

你可以做到以下幾點:

Calendar cal=Calendar.getInstance(); 
    int currentDay=cal.get(Calendar.DAY_OF_MONTH); 
    //Set the date to 2 days ago 
    cal.set(Calendar.DAY_OF_MONTH, currentDay-2); 

那麼你就可以獲取日期:

cal.getTime(); //The date 2 days ago 
+0

哦坦克你!!它工作得很好! :) –

10

一個更好的辦法是使用add方法而不是set

cal.add(DAY_OF_YEAR, -2); 
即,

也就是說以確保它的工作原理也是第一天月等

1

同一種代碼,但使用Joda-Time 2.3庫和Java 7

DateTime dateTime = new DateTime(2014, 2, 3, 7, 8, 9); 
DateTime twoDaysPrior = dateTime.minusDays(2); 
dateTime: 2014-02-03T07:08:09.000-08:00 
twoDaysPrior: 2014-02-01T07:08:09.000-08:00 
2

我用下面的功用:

public static Date getStartOfDay() { 
    Calendar calendar = Calendar.getInstance(); 
    calendar.setTime(new Date()); 
    calendar.set(Calendar.HOUR_OF_DAY, 0); 
    calendar.set(Calendar.MINUTE, 0); 
    calendar.set(Calendar.SECOND, 0); 
    calendar.set(Calendar.MILLISECOND, 0); 
    return calendar.getTime(); 
} 

public static long getDaysAgo(Date date){ 
    final long diff = getStartOfDay().getTime() - date.getTime(); 
    if(diff < 0){ 
    // if the input date millisecond > today's 12:00am millisecond it is today 
    // (this won't work if you input tomorrow) 
     return 0; 
    }else{ 
     return TimeUnit.MILLISECONDS.toDays(diff)+1; 
    } 
}