You can use SimpleDateFormat
as shown below:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, days); // +days
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
return formatter.format(cal.getTime());
Demo:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
class Main {
public static void main(String[] args) {
System.out.println(toFormattedString(10, "dd-MMM-yyyy"));
System.out.println(toFormattedString(10, "dd-MM-yyyy"));
}
static String toFormattedString(int days, String pattern) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, days); // +days
SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.getDefault());
return formatter.format(cal.getTime());
}
}
Output:
18-Feb-2021
18-02-2021
The date-time API of java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
Using the modern date-time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
System.out.println(toFormattedString(10, "dd-MMM-uuuu"));
System.out.println(toFormattedString(10, "dd-MM-uuuu"));
}
static String toFormattedString(int days, String pattern) {
LocalDate today = LocalDate.now();
LocalDate afterTenDays = today.plusDays(days); // +days
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.getDefault());
return formatter.format(afterTenDays);
}
}
Output:
18-Feb-2021
18-02-2021
Learn more about the modern date-time API from Trail: Date Time.