Java根據當前日期獲得這一週的日期,不是很經常用,但是用起來又不是很好找的代碼!
/**
* 測試
* @param args
*/
public static void main(String[] args) {
// 定義輸出日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd EEE");
Date currentDate = new Date();
// 比如今天是2012-12-25
List<Date> days = dateToWeek(currentDate);
System.out.println("今天的日期: " + sdf.format(currentDate));
for (Date date : days) {
System.out.println(sdf.format(date));
}
}
/**
* 根據日期獲得所在周的日期
* @param mdate
* @return
*/
@SuppressWarnings("deprecation")
public static List<Date> dateToWeek(Date mdate) {
int b = mdate.getDay();
Date fdate;
List<Date> list = new ArrayList<Date>();
Long fTime = mdate.getTime() - b * 24 * 3600000;
for (int a = 1; a <= 7; a++) {
fdate = new Date();
fdate.setTime(fTime + (a * 24 * 3600000));
list.add(a-1, fdate);
}
return list;
}
結果如下: