Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Calendar: calculate start date and end date of the previous week

Tags:

java

What is most convenient and shortest way to get start and end dates of the previous week? Example: today is 2011-10-12 (input data),but I want to get 2011-10-03 (Monday's date of previous week) and 2011-10-09 (Sunday's date of previous week).

like image 247
adrift Avatar asked Oct 12 '11 15:10

adrift


2 Answers

Here's another JodaTime solution. Since you seem to want Dates only (not timestamps), I'd use the DateMidnight class:

final DateTime input = new DateTime();
System.out.println(input);
final DateMidnight startOfLastWeek = 
    new DateMidnight(input.minusWeeks(1).withDayOfWeek(DateTimeConstants.MONDAY));
System.out.println(startOfLastWeek);
final DateMidnight endOfLastWeek = startOfLastWeek.plusDays(6);
System.out.println(endOfLastWeek);

Output:

2011-10-12T18:13:50.865+02:00
2011-10-03T00:00:00.000+02:00
2011-10-10T00:00:00.000+02:00
like image 169
Sean Patrick Floyd Avatar answered Oct 27 '22 00:10

Sean Patrick Floyd


public static Calendar firstDayOfLastWeek(Calendar c) {
    c = (Calendar) c.clone();
    // last week
    c.add(Calendar.WEEK_OF_YEAR, -1);
    // first day
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
    return c;
}

public static Calendar lastDayOfLastWeek(Calendar c) {
    c = (Calendar) c.clone();
    // first day of this week
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
    // last day of previous week
    c.add(Calendar.DAY_OF_MONTH, -1);
    return c;
}
like image 42
jarnbjo Avatar answered Oct 27 '22 00:10

jarnbjo