I need to build a date format like dd/MM/yyyy
. It's almost like DateFormat.SHORT
, but contains 4 year digits.
I try to implement it with
new SimpleDateFormat("dd//MM/yyyy", locale).format(date);
However for US locale the format is wrong.
Is there a common way to format date that changes pattern based on locale?
Thank you
java.time
Here’s the modern answer. IMHO these days no one should struggle with the long outdated
DateFormat
andSimpleDateFormat
classes. Their replacement came out in the modern Java date & time API early in 2014, the java.time classes.I am just applying the idea from Happier’s answer to the modern classes.
The
DateTimeFormatterBuilder.getLocalizedDateTimePattern
method generates a formatting pattern for date and time styles for aLocale
. We manipulate the resulting pattern string to force the 4-digit year.Example output:
Locale.US
:7/18/2017
.UK
,FRANCE
,GERMANY
andITALY
:18/07/2017
.DateTimeFormatterBuilder
allows us to get the localized format pattern string directly, without getting a formatter first, that’s convenient here. The first argument togetLocalizedDateTimePattern()
is the date format style.null
as second argument indicates that we don’t want any time format included. In my test I used aLocalDate
fordate
, but the code should work for the other modern date types too (LocalDateTime
,OffsetDateTime
andZonedDateTime
).I would do it like this:
Using a FieldPosition you don't really have to care about wheter the format of the date includes the year as "yy" or "yyyy", where the year ends up or even which kind of separators are used.
You just use the begin and end index of the year field and always replace it with the 4 digit year value and that's it.
I have similar way to do this, but I need to get the locale pattern for the ui controller.
So here's the code
Can you not just use java.text.DateFormat class ?
That should do what you want to do.