I've been looking at the Date and Time library in Java 8 and was wondering if there is a way to format the date to the local format regardless of where the program is being run (as in, using the local format of the region the computer is set to).
The Date and Time library uses the LocalDate class for getting a date. Using LocalDate.now()
uses the yyyy-MM-dd format by default.
This can be formatted using a DateTimeFormatter like so:
DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate date = LocalDate.now().format(dtFormatter);
Unfortunately, this relies entirely on the pattern I enter in the ofPattern(pattern)
method.
There is also a ofPattern(pattern, locale)
method which allows a locale to be used, however using the following code does not format as I would like as it does not convert the date to the US format of MM-dd-yyyy:
DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy", Locale.US);
LocalDate date = LocalDate.now().format(dtFormatter);
If this did work, I would try using Locale.getDefault()
. Unfortunately it doesn't appear to change anything.
So is there any way using the Java 8 Date and Time library to convert a date into the format used by the location that the program is currently running. For example, if I was in the US, I would get the MM-dd-yyyy format; but if my computer's locale was set to the UK, the date would be given as dd-MM-yyyy.
EDIT: I forgot to mention, I've tried the solution given to this question, however this formats the date as dd/MM/yy, however I would prefer it as dd-MM-yyyy. I can change each / into a - using replaceAll("/","-")
, however this does not convert the year from yy to yyyy format.