Is there any way to make DateFormat
format a date with a full year (eg. 12/12/2010), when using DateFormat.SHORT
as the pattern? I have to format dates in both en_US and da_DK.
I know I could use DateFormat.MEDIUM
, but the date have to be formatted using only numbers and separators, and DateFormat.MEDIUM
for en_US produces something like 'Dec 12, 2010'.
This is a friendly reminder that when formatting dates in Java's SimpleDateFormat class there is a subtle difference between YYYY and yyyy. They both represent a year but yyyy represents the calendar year while YYYY represents the year of the week.
DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass, such as SimpleDateFormat , allows for formatting (i.e., date -> text), parsing (text -> date), and normalization.
SimpleDateFormat – yyyy-M-d For legacy Java application, we use SimpleDateFormat and . setLenient(false) to validate a date format.
Java SimpleDateFormat ExampleString pattern = "MM-dd-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat. format(new Date()); System. out. println(date);
If both formats are the same, then simply use:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
If they differ:
private static Map<Locale, String> formats = new HashMap<Locale, String>();
static {
formats.put(new Locale("en_US"), "MM/dd/yyyy");
formats.put(new Locale("da_DK"), "dd.MM.yyyy");
}
And then instead of using DateFormat.getDateInstance(..)
use
new SimpleDateFormat(formats.get(locale)).format(..);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With