jujil lokoko
jujil lokoko

Reputation: 35

how to convert localDateTime to string date DD/MM/YYYY

I have data localDateTime in java like this

localDateTime localDateTime = 2022-01-04 14:59:20.207;

How to convert it to format DD/MM/YYYY ?

Upvotes: 0

Views: 3727

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338211

tl;dr

LocalDateTime
.parse( 
    "2022-01-04 14:59:20.207".replace( " " , "T" ) 
)
.toLocalDate()
.format ( 
    DateTimeFormatter
    .ofLocalizedDate( FormatStyle.SHORT )
    .withLocale( Locale.FRANCE )
)

Details

Parse your input string. Replace the SPACE in the middle with a T to comply with the ISO 8601 standard format.

LocalDateTime ldt = LocalDateTime.parse( "2022-01-04 14:59:20.207".replace( " " , "T" ) ) ;

Extract a date.

LocalDate ld = ldt.toLocalDate() ;

Generally best to automatically localize rather than hard-code a formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.FRANCE ) ;
String output = ld.format ( f ) ;

04/01/2022

Or hard-code a specific formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;

Upvotes: 1

Related Questions