0

How can I convert a Java string to a date in this format - "31 Jan 2022". I've tried the code below.

Date sDate;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
sDate = format.parse("20/12/2002");
return sDate.toString();  

It's giving an output in this format "Fri Jan 30 00:00:00" which is not what I want

9
  • You should be getting the error java.text.ParseException: Unparseable date: "31 Jan 2022". "31 Jan 2022" is not in the format "dd/MM/yyyy". Are you sure that your input is what you say it is? Commented Aug 1, 2022 at 11:10
  • 2
    Please do not use Date and SimpleDateFormat, as they are obsolete classes. They're also troublesome. You are better off using classes from the java.time package. In your case, where you only seem to need a date without time and timezone, you may want to use LocalDate. Commented Aug 1, 2022 at 11:20
  • @OHGODSPIDERS please review the code again, I just made an edit. Commented Aug 1, 2022 at 15:17
  • 2
    ❶ Define your format as a String ❷ Pass this string as an argument to DateTimeFormatter::ofPattern ❸ Use your string and the DateTimeFormatter instance as arguments to LocalDate::parse. Commented Aug 1, 2022 at 15:22
  • 1
    If you want to output a Date, or LocalDate in a specific format, you will always have to create a String representation yourself and output that String. There simply is no way to "save" a format in a Date object and have it use that in its default toString() method that is used when you print it. See: display Java.util.Date in a specific format on how to format your Date object into a String. Commented Aug 1, 2022 at 15:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.