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.