JohnnySmith88
JohnnySmith88

Reputation: 301

Date time format in Spring

I want to get the current date and time in Spring and format it. I use LocalDateTime to get the current date, but it is like this: 2021-08-23T18:24:36.229362200

And want to get it in this format: "MM/dd/yyyy h:mm a" I tried this:

    LocalDateTime localDateTime = LocalDateTime.now(); //ziua de azi
    String d = localDateTime.toString();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM//dd//yyyy h:mm a");
    localDateTime = LocalDateTime.parse(d, formatter);

But I get the following error:

Text '2021-08-23T18:26:37.002166200' could not be parsed at index 2

Please how can I format it?

Upvotes: 3

Views: 2242

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338574

tl;dr

ZonedDateTime
.now()
.format(
    DateTimeFormatter.ofPattern( "MM/dd/uuuu h:mm a" )   
)

Or, better to be explicit rather than rely implicitly on defaults. And perhaps better to automatically localize.

ZonedDateTime
.now(
    ZoneId.of( "Europe/Bucharest" )
)
.format(
    DateTimeFormatter
    .ofLocalizedDateTime( FormatStyle.SHORT ) 
    .withLocale( 
        new Locale( "ro" , "RO" )   // Romanian in Romania.
    )
)

See this code run live at IdeOne.com.

24.08.2021, 04:09

Using Locale.US instead produces:

8/24/21, 4:11 AM

Details

I cannot imagine a scenario where calling LocalDateTime.now() is the right thing to do. That class lacks any concept of time zone or offset, so it cannot represent a specific moment in time.

To represent a moment, a specific point on the time line, use Instant, OffsetDateTime, or ZonedDateTime.

To capture the current moment as seen in a particular time zone, use ZonedDateTime.

ZoneId z = ZoneId.systemDefault() ;  // Or specify a zone. 
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

Let java.time automatically localize for you.

Locale locale = new Locale( "ro" , "RO" ) ;  // For Romanian in Romania. Or `Locale.US`, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatSyle.SHORT ).withLocale( locale );
String output = zdt.format( f ) ;

Or you can hard-code a specific format. Do not use pairs of slash characters as seen in Question.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu h:mm a" ) ;

I see nothing specific about Spring in your Question or code. These are general Java issues.

Upvotes: 5

Mahesh
Mahesh

Reputation: 355

LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy h:mm a");
String formattedDate = localDateTime.format(formatter);
System.out.println(formattedDate);

Upvotes: 2

Related Questions