Home > Mobile >  Converting String to Date in Java in specific format [closed]
Converting String to Date in Java in specific format [closed]

Time:10-05

How to convert string 210101 to Date 01 January 2021 in java?? I have tried like the below:

String string="210101"
SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
Date date=formatter.parse(string);

CodePudding user response:

You can do it like so using the Java Time package classes. You should not be using Date as it is flawed and obsolete.

String string="210101";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyMMdd");
LocalDate localDate = LocalDate.parse(string, dtf);

This prints the date in the default format specified by toString()

System.out.println(localDate);

And this uses your pattern.

System.out.println(localDate.format(dtf));

the output is

2021-01-01
210101

You can also specify the following as in your question.


DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("dd MMMM yyyy");
System.out.println(localDate.format(outputFormat));

prints

01 January 2021

Finally, if you really want a Date instance (which I recommend against), you can do the following:

Date date = Date.valueOf(localDate);

CodePudding user response:

String string="210101";
SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
java.util.Date date=formatter.parse(string);
System.out.println(date);
  • Related