Skip to main content

APIzation: Replication Package

[Q#745443][A#745451] How to determine the date one day prior to a given date in Java?

https://stackoverflow.com/q/745443

I am assuming Java has some built-in way to do this. Given a date, how can I determine the date one day prior to that date? For example, suppose I am given 3/1/2009. The previous date is 2/28/2009. If I had been given 3/1/2008, the previous date would have been 2/29/2008.

Answer

https://stackoverflow.com/a/745451

Use the Calendar interface. Doing "addition" in this way guarantees you get a valid date. This is valid for 1st of the year as well, e.g. if myDate is January 1st, 2012, oneDayBefore will be December 31st, 2011.

APIzation

Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.DAY_OF_YEAR,-1);
Date oneDayBefore= cal.getTime();
package com.stackoverflow.api;

import java.util.Calendar;
import java.util.Date;

public class Human745451 {

  public static Date getDayBefore(Date myDate) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(myDate);
    cal.add(Calendar.DAY_OF_YEAR, -1);
    return cal.getTime();
  }
}

package com.stackoverflow.api;

import java.util.Calendar;
import java.util.Date;
import java.util.Date;

/**
 * How to determine the date one day prior to a given date in Java?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/745451">https://stackoverflow.com/a/745451</a>
 */
public class APIzator745451 {

  public static Date determineDate(Date myDate) throws Exception {
    Calendar cal = Calendar.getInstance();
    cal.setTime(myDate);
    cal.add(Calendar.DAY_OF_YEAR, -1);
    return cal.getTime();
  }
}