-4

I'm able to calculate future date using

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, days); // +days      
    return cal.getTime();

but the returned date format is : Fri Nov 23 12:09:46 PST 2018

how to override it with dd-mmm-yyyy format ??

azro
  • 53,056
  • 7
  • 34
  • 70
rev
  • 11

1 Answers1

0

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Unmitigated
  • 76,500
  • 11
  • 62
  • 80