-3
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
date1 = dateFormat.format(new Date(date));
System.out.println(date+" "+date1);

My input is date = 30-Dec-2019 and the expected output is 2019-12-30

The output I'm getting is 2020-12-30

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Do not longer use the old simpledateformat and java.util.Date Api. Use the new java.times.* API. And yyyy instead of YYYY. – Jens May 05 '20 at 17:26
  • If you want help with your code using the obsolete API, at least post code that compiles. – David Conrad May 05 '20 at 17:27
  • The deprecated `Date(String)` constructor doesn't accept input in that format. – David Conrad May 05 '20 at 17:31
  • I recommend (1) Don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). (2) Even if you insist on using `Date`, stay far away from the deprecated constructors. They have been deprecated for over 23 years because they work unreliably across time zones. – Ole V.V. May 05 '20 at 17:51
  • 1
    using small yyyy i solve this issue – ambaliya jignesh May 06 '20 at 04:16

1 Answers1

1

Do not use the outdated date/time API. Do it using modern date/time API as follows:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {

    public static void main(String[] args) throws Exception {
        DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
        DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String strDate = "30-Dec-2019";
        LocalDate date = LocalDate.parse(strDate, inputFormat);
        System.out.println(outputFormat.format(date));
    }
}

Output:

2019-12-30

Check this to learn about the drawbacks of the outdated date/time API and the benefits of modern date/time API.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110