Using below code, you can add days to any specific date and find out the new date in any date format.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class PlusDays {
public static void main(String[] args) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); // "dd/MM/yyyy" is the date
format , you can use any date format , month should be using capitol "M" only , not small "m".
Calendar cal = Calendar.getInstance();
cal.setTime(dateFormat.parse("01/01/2019")); // you will add days in this date
cal.add(Calendar.DAY_OF_MONTH, 2); // add 2 days
String newDateFromGivenDate =
dateFormat.format(cal.getTime());
System.out.println("new Date after adding 2 days = "+newDateFromGivenDate);
}
}
new Date after adding 2 days = 03/01/2019
Let's give a different date format:
public class PlusDays {
public static void main(String[] args) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/dd/MM"); // "dd/mm/yyyy" is the date
format , you can use any date format .
Calendar cal = Calendar.getInstance();
cal.setTime(dateFormat.parse("2019/01/01")); // you will add days in this date
cal.add(Calendar.DAY_OF_MONTH, 2); // add 2 days
String newDateFromGivenDate =
dateFormat.format(cal.getTime());
System.out.println("new Date after adding 2 days = "+newDateFromGivenDate);
}
}
Output:
new Date after adding 2 days = 2019/03/01
No comments:
Post a Comment