Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localized date format in Java

I have a timestamp in millis and want to format it indicating day, month, year and the hour with minutes precission.

I know I can specify the format like this:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy HH:mm");
String formatted = simpleDateFormat.format(900000)

But I'd like the format to be localized with the user's locale. I've also tried

DateFormat DATE_FORMAT = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
DATE_FORMAT.format(new Date());

But it does not show the hour. How can I do it?

like image 227
Addev Avatar asked Nov 30 '22 20:11

Addev


1 Answers

Is using joda time (http://joda-time.sourceforge.net/) out of the question? If not, then I would wholeheartedly recommend using this wonderful library instead of the cumbersome Java API.

If not, you could use DateFormat.getDateTimeInstance(int, int, Locale)

The first int is the style for hour, the other is the style for time, so try using:

DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
String formattedDate = f.format(new Date());
System.out.println("Date: " + formattedDate);

See if this suits you.

Output for Locale.GERMANY: Date: 25.07.13 10:57

Output for Locale.US: Date: 7/25/13 10:57 AM

like image 92
theadam Avatar answered Dec 05 '22 19:12

theadam