Home > Enterprise >  SimpleDateFormat returns wrong date in java
SimpleDateFormat returns wrong date in java

Time:03-31

private String dateFormatter(String olddate) {
   String newDate = "";
   try {
       SimpleDateFormat initDate = new SimpleDateFormat("dd-MMM-yy - HH:mm");
       SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy - HH:mm");
       newDate = formatter.format(initDate.parse(olddate));
   } catch (ParseException e) {
       e.printStackTrace();
   }
   return newDate;
}

Input Date is : 29-Mar-22 - 22:00 Required Output Date is : 29/03/22 - 22:00

Instead of this I will get parse exception When I convert current date in dd-MMM-yy - HH:mm format it returns 29-M03-22 - 11:38 Which is wrong.

So please help me to solve this issue.

Thanks in advance.

CodePudding user response:

This worked for me.

import java.util.*;
import java.text.*;

public class Demo{
   public static void main(String args[]) throws Exception{
      String oldDate = "29-Mar-22 - 22:00";
      SimpleDateFormat initDate = new SimpleDateFormat("dd-MMM-yy - HH:mm");
      SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy - HH:mm");
      String newDate = formatter.format(initDate.parse(oldDate));
      System.out.println("oldDate: " oldDate);
      System.out.println("newDate: " newDate);
   }
}

This is the output I got while trying it on jdoodle.com

CodePudding user response:

Be sure your formatting pattern is using the letter M from the US-ASCII range of Unicode, as commented by Dawood ibn Kareem.

java.time

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

LocalDateTime
.parse(
    "29-Mar-22 - 22:00" ,
    DateTimeFormatter.ofPattern( "dd-MMM-uu - HH:mm" ).withLocale( Locale.US ) 
)
.format(
    DateTimeFormatter.ofPattern( "dd/MM/uu - HH:mm" )
)

Tip: Use four digit years. In my experience, saving two digits of space is not worth the confusion caused by the ambiguity.

Tip: Rather than hard-code such formats, (a) use only standard ISO 8601 formats for data exchange, and (b) let java.time automatically localize when producing string values for presentation to the user.

  • Related