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.
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.
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
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));