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?
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
But it does not show the hour. How can I do it?
You have to call DateFormat.getDateTimeInstance(int, int, Locale)
DateFormat.getDateInstance(int, Locale)
=> Gets the date formatter with the given formatting style for the given locale.
While
DateFormat.getDateTimeInstance(int, int, Locale)
=> Gets the date/time formatter with the given formatting styles for the given locale.
Try some thing like this
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy HH:mm", Locale.getDefault());
String formatted = simpleDateFormat.format(900000);
System.out.println(simpleDateFormat.parse(formatted));
You can use method getDateTimeInstance
, of DateFormat
. Here the getDateTimeInstance
method takes 3 arguments
- the style of Date field
- the style of time field
the Locale using which pattern is auto extracted
DATE_FORMAT = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US);
System.out.println(DATE_FORMAT.format(d));
DATE_FORMAT = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.FRENCH);
System.out.println(DATE_FORMAT.format(d));
You can use something like this:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy HH:mm", Locale.getDefault());
String formatted = sdf .format(900000);
System.out.println(simpleDateFormat.parse(formatted));
Using Joda-Time you could detect the system setting and use different time format:
String format;
if (DateFormat.is24HourFormat(context)) {
format = "MM/dd/yy, hh:mm";
}
else {
format = "MM/dd/yy, h:mm aa";
}
DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
formatter.print(new DateTime());