Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I convert String date to Date format date in dd-MM-yyyy format in java

I have date in string format as Wed Jun 07 00:00:00 IST 2023 but I want it as in dd-mm-yyyy format in DATE type only… I can convert it but it is converting in String type I want it should convert it into ONLY Date type in dd-mm-yyyy format.

I tried below code but it is converting in String format as Wed Jun 07 00:00:00 IST 2023 but I want output should be something like

Date date = 07-06-2023 only.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please help me.

My code snippet is:

public static void main(String[] args) throws ParseException {
String dateOfBirht= "07-06-2023";
Date date = new SimpleDateFormat("dd-MM-yyyy").parse(dateOfBirht);
System.out.println(date);

If you see the output of the above code snippet is printing as Wed Jun 07 00:00:00 IST 2023 which is not my desired answer. It should be 07-06-2023 in DATE FORMAT ONLY neither String nor LocaleDate

>Solution :

"… I want it as in dd-mm-yyyy format in DATE type only. …"

I’m not sure I understand the question, entirely.  You already have the Date value, here.

Date date = new SimpleDateFormat("dd-MM-yyyy").parse(dateOfBirht);

"… If you see the output of the above code snippet is printing as Wed Jun 07 00:00:00 IST 2023 which is not my desired answer. It should be 07-06-2023 …"

I believe you’re implying that the Date object should not be returning the time, since you had only parsed the date values.

This isn’t the case.  Similarly, it is still a valid date; the zeroed time fields should play no role in the date fields.

Nevertheless, you can use a basic String format.
Format specifiers can be found on the Formatter class JavaDoc.

System.out.printf("%td-%1$tm-%1$tY", date);

Output

07-06-2023
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading