0

i have a variable which gives me random dates in this format `"dd/MM/yyyy".I want my code to add 5 days in this date like this.

05/12/2022 ---> 10/12/2022

The code i found on internet is this

String stringDate="05/12/2022";
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(stringDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
cal.add(Calendar.DATE, 5);
Date dateWith5Days = cal.getTime();
System.out.println(dateWith5Days+" is the date after adding 5 days.");

Output

Sat Dec 10 00:00:00 IST 2022 is the date after adding 5 days.

Expected output

10/12/2022 is the date after adding 5 days.
Muhammad
  • 59
  • 9
  • 4
    Don't use Date, there are far better DateTypes to use nowadays. If you want that output, you'll need to apply a formatter. – Stultuske Dec 05 '22 at 07:46

1 Answers1

3

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.

Define a custom format to match your input and output.

DateTimeFormatter f  = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;

Parse input using that format.

LocalDate ld = LocalDate.parse( input , f ) ;

Add five days. Notice how these classes use immutable objects. We instantiate a second LocalDate object rather than mutate the original.

LocalDate fiveDaysLater = ld.plusDays( 5 ) ;

Generate text in your desired format.

String output = fiveDaysLater.format( f ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154