Get last week date range for a date in Java

this is Java Calendar based solution

    Date date = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    int i = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
    c.add(Calendar.DATE, -i - 7);
    Date start = c.getTime();
    c.add(Calendar.DATE, 6);
    Date end = c.getTime();
    System.out.println(start + " - " + end);

output

Mon Jun 10 13:22:01 EEST 2013 - Sun Jun 16 13:22:01 EEST 2013

it’s localized, in my Locale week starts with Monday


要知道今天是不是 周日,可以用這一段 sample code:

DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
Calendar now = new GregorianCalendar();
Calendar start = new GregorianCalendar(now.get(Calendar.YEAR), 
        now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH) );

while (start.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
    start.add(Calendar.DAY_OF_WEEK, -1);
}

Calendar end = (Calendar) start.clone();
end.add(Calendar.DAY_OF_MONTH, 7);

System.out.println(df.format(now.getTime()) );
System.out.println(df.format(start.getTime()) );
System.out.println(df.format(end.getTime()) );

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *