java – How to change the date 1 day ago

Question:

i have a variable

String date = "10.11.2016";

how do i convert it to

String date = "09.11.2016";

It needs to be done for any date. How can this be done?

Answer:

First, you need to get a representation of a given date in the form of a class object that is designed to work with dates. This class is the Calendar class.

You get an instance of the Calendar class:

Calendar calendar = Calendar.getInstance();

Create an object that converts a date as a string (of a specific format) to an object of the Date class:

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

Get a Date class object from your string and initialize calendar :

calendar.setTime(sdf.parse(date));

Modify the calendar object by decrementing the date:

calendar.add(Calendar.DATE, -1);

Get the text representation of the calendar object:

date = sdf.format(calendar.getTime());
Scroll to Top