Home > Net >  how to format String to Date with format dd-mm-yyyy in java
how to format String to Date with format dd-mm-yyyy in java

Time:05-14

I need some support. I desired convert a variable String to Date. The variable Date should be format dd-MM-yyyy.

 import java.util.Date;
    ....
    ...
    String a = "2022-05-12";
    Date b; // should be dd-MM-yyyy 
    
    do some to format...
    
    return b; // return b with format dd-MM-yyyy, remember this variable is type Date no String

I was trying to do something but the format obtained is not the desired one.

enter image description here

CodePudding user response:

tl;dr

LocalDate
.parse( "2022-05-12" )
.format(
    DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)

12-05-2022

java.time

Use modern java.time classes. Never use the terrible Date, Calendar, SimpleDateFormat classes.

ISO 8601

Your input conforms to ISO 8601 standard format used by default in the java.time classes for parsing/generating text. So no need to specify a formatting pattern.

LocalDate

Parse your date-only input as a date-only object, a LocalDate.

String input = "2022-05-12" ;
LocalDate ld = LocalDate.parse( input ) ;

To generate text in your desired format, specify a formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = ld.format( f ) ;

Rather than hardcode a particular pattern, I suggest learning to automatically localize using DateTimeFormatter.ofLocalizedDate.

All this has been covered many many times already on Stack Overflow. Always search thoroughly before posting. Search to learn more.

CodePudding user response:

What you are doing is converting from string to date. It seems that you want it to PRINT the date in a specific format.

Where is an example of how to do it:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2022/05/18 00:18:43
  • Related