-3

I have a date variable in the YYYY-MM-DD format.

How can I change the date value to the previous day? So if the value of the variable was 2014-01-01 it would change to 2014-12-31.

wildWill
  • 37
  • 1
  • 7

2 Answers2

3

You can use a DateFormat and a Calendar, like so

String fmt = "yyyy-MM-dd";
String dt = "2014-01-01";
java.text.DateFormat df = new java.text.SimpleDateFormat(fmt);
java.util.Calendar cal = java.util.Calendar.getInstance();
try {
    cal.setTime(df.parse(dt));
    cal.add(java.util.Calendar.DAY_OF_MONTH, -1);
    System.out.println(cal.getTime());
} catch (Exception e) {
}

Which outputs

Tue Dec 31 00:00:00 EST 2013
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Java can parse a date, then subtract one day and output the toString()

documentation: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Date.html

Long version:

String example = "2014-01-01";
DateFormat df = new SimpleDateFormat("YYY-MM-dd", Locale.ENGLISH);
Date result =  df.parse(target);
Calendar cal = Calendar.getInstance();
cal.setTime(result);
cal.add(Calendar.DATE, -1);
result = cal.getTime();
System.out.println(df.format(result));
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Would you care to elaborate on _how_ to do this? Also, the javadoc you linked to is very outdated, use http://docs.oracle.com/javase/7/docs/api/ instead. – The Guy with The Hat Jan 21 '14 at 21:48