-2

I am trying to convert "2019-04-24" to "24-Apr-2019" this but it is converting it as "24-Jan-19".

This is the code I am using:

public static String dateFormatConvert(String date, String srcDateFormat, String targetDataFormat) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat(srcDateFormat);
    Date srcDate = dateFormat.parse(date);
    DateFormat destDateFormat = new SimpleDateFormat(targetDataFormat);
    return destDateFormat.format(srcDate);
}

Calling it:

    String date1 = CommonUtil.dateFormatConvert("2019-04-24", "yyyy-MM-DD", "DD-MMM-YY"); -> This is one of the format used (DD-MMM-YY) out of many
    System.out.println(date1);

What's going wrong here?

QualityMatters
  • 895
  • 11
  • 31
  • 4
    Hint: did you read the `SimpleDateFormat` documentation *very carefully* when coming up with your format strings? What does `DD` mean, according to that documentation, and what did you expect it to mean? – Jon Skeet Sep 08 '21 at 15:33
  • 2
    Step 1: Use `java.time` instead. – chrylis -cautiouslyoptimistic- Sep 08 '21 at 15:35
  • 3
    Use LocalDate.of to set specific date then use DateTimeFormatter.ofpattern to specify the pattern u like dd MMM yyyy – adam Sep 08 '21 at 15:51
  • https://stackoverflow.com/questions/42175899/java-8-datetimeformatter – Abra Sep 08 '21 at 15:52
  • 1
    Besides `DD` instead of `dd`, use of `YY` instead of `yy` or `yyyy` is also wrong. – Mark Rotteveel Sep 08 '21 at 15:58
  • 2
    `java.time.LocalDate.parse( "2019-04-24" ).format( DateTimeFormatter.ofPattern( "dd-MMM-uuuu" ).withLocale( Locale.US ) )` See this [code run live at IdeOne.com](https://ideone.com/XwW8qC). Use only *java.time* classes. Never use `Date`/`Calendar`. – Basil Bourque Sep 08 '21 at 16:28
  • 1
    I too recommend you 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/). – Ole V.V. Sep 08 '21 at 16:46
  • 1
    Also don’t keep your dates in strings and don’t convert them from one sting format to another. Keep your dates in `LocalDate` objects and only format them into strings when you need a string, like for presentation to the user. – Ole V.V. Sep 08 '21 at 16:48

1 Answers1

1

According to the Documentation.

D - Day in year

d - Day in month

The correct code would be:

date1 = dateFormatConvert("2019-04-24", "yyyy-MM-dd", "dd-MMM-yyyy");
Tomas Alves
  • 60
  • 1
  • 10