How to find previous date if current date is given as a String? Below is given my code. Is there any shorter solution?
private static String previousDay(String date) {
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
String newDate = "";
if (day > 1 & month > 1)
newDate = year+"-"+month+"-"+(day-1);
else if (day == 1 & month > 1) {
Calendar calendar = new GregorianCalendar(year,month-1, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
newDate = year+"-"+(month-1)+"-"+daysInMonth;
} else if (day == 1 & month == 1) {
Calendar calendar = new GregorianCalendar(year,12, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
newDate = year+"-"+12+"-"+daysInMonth;
}
return newDate;
}
You need to convert your String to Date, in order to do date calculations. You can use Calender to find previous day. From your code, I assume, your date format is yyyy-MM-dd.