How to display date format according to locale?

2019-04-09 06:53发布

I want to display a hint how a date should be entered. For Germany it might look like

"Enter date in this format: dd.mm.yyy"

For the US

"Enter date in this format: mm/dd/yyyy"

I understand that with

DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context);

I can convert a date into a format matching the user's locale. But how would I get the day/month/year string for the hint?

And of course I would want the similar thing with a hint for time, too.

Thanks for any suggestions.

4条回答
我命由我不由天
2楼-- · 2019-04-09 07:31

You can use the getBestDateTimePattern method of DateFormat:

String datePattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "ddMMyyyy");
String timePattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "HHmmss");

note: assumes 24-hour format for the time. You might want to convert to all upper or lower case before presentation to the user.

查看更多
劫难
3楼-- · 2019-04-09 07:38
String hintText = new SimpleDateFormat().toPattern(); // dd/MM/y HH:mm

I know you were asking for just the date, but this was as close as I can get. The internal rule is localeData.getDateFormat(SHORT) + " " + localeData.getTimeFormat(SHORT) so I guess as long as there is not a locale that has a date format with spaces on it, you can just split the string on a space

查看更多
Animai°情兽
4楼-- · 2019-04-09 07:50

Wouldn't it be easier to get you date with a date picker: http://developer.android.com/guide/topics/ui/controls/pickers.html#DatePicker

If not, then take a look at this: https://stackoverflow.com/a/11093572/3965178

查看更多
一夜七次
5楼-- · 2019-04-09 07:51

Try this:

    Calendar cal = Calendar.getInstance();
                            int year = cal.get(Calendar.YEAR);
                            int month = cal.get(Calendar.MONTH);
                            int day = cal.get(Calendar.DAY_OF_MONTH);
                            int hour = cal.get(Calendar.HOUR_OF_DAY);
                            int minute = cal.get(Calendar.MINUTE);
                            int second = cal.get(Calendar.SECOND);

Calendar now = new GregorianCalendar(year, month, day, hour, minute, second);

long time = now.getTimeInMillis();
Date date = new Date(time);

String timeSet = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date);
查看更多
登录 后发表回答