Ian Ian - 1 year ago 64
Java Question

If I have a specific date of a day, how do I get the date of that day in the previous week?

For example, if I have a "Date" variable "date1" with a value of (dd/mm/yyy) 03/07/2011, which is a Sunday. How do I get the "Date" of the previous Sunday "date2"? which would have the value (dd/mm/yyyy) 26/06/2011.

Is there an easy way of doing it, for example:

pseudo code:

Date date1 = (03/07/2011);
Date date2 = date1.subtractNumberOfDays(7);

Answer Source

You should use Calendar:

    Calendar date = new GregorianCalendar(2011, Calendar.JULY, 3);
    date.add(Calendar.DAY_OF_MONTH, -7);

You can create a calendar from date too:

    Date date1 = new Date(2011, Calendar.JULY, 3);
    Calendar date = new GregorianCalendar();
    date.add(Calendar.DAY_OF_MONTH, -7);
    date2 = date.getTime();

Be aware that:

  • Java uses 0 to represent January !
  • Date(year, month, day) is deprecated since JDK version 1.1 !

See the GregorianCalendar JavaDoc:

Constructs a GregorianCalendar with the given date set in the default time zone with the default locale. Parameters: year the value used to set the YEAR calendar field in the calendar. month the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g., 0 for January. dayOfMonth the value used to set the DAY_OF_MONTH calendar field in the calendar.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download