Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java DateFormat.SHORT with full year

Tags:

java

date

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'.

like image 278
ManiSto Avatar asked Aug 31 '10 11:08

ManiSto


People also ask

What is the difference between YYYY and YYYY in Java?

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.

What is DateFormat short?

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.

How do you check if the date is in YYYY MM DD format in Java?

SimpleDateFormat – yyyy-M-d For legacy Java application, we use SimpleDateFormat and . setLenient(false) to validate a date format.

How do you change date format to MM DD YYYY in Java?

Java SimpleDateFormat ExampleString pattern = "MM-dd-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat. format(new Date()); System. out. println(date);


1 Answers

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(..);
like image 69
Bozho Avatar answered Oct 09 '22 18:10

Bozho