5

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.

Addi
  • 1,099
  • 1
  • 12
  • 17

4 Answers4

5

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.

samgak
  • 23,944
  • 4
  • 60
  • 82
  • Works like a charm, unfortunately only from API level 18 (http://developer.android.com/reference/android/text/format/DateFormat.html#getBestDateTimePattern(java.util.Locale, java.lang.String)) onwards. Seems I need to go with the solution @WORMSS suggested – Addi Mar 19 '15 at 20:58
3
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

WORMSS
  • 1,625
  • 28
  • 36
  • Yes works. I have to see, what to do with potentially more than on blank in the result string. Thank you. – Addi Mar 19 '15 at 21:03
  • I believe samgak solution is better than my own. But as you have stated in the comments, It's API 18+ – WORMSS Mar 20 '15 at 11:06
2

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);
MorZa
  • 2,215
  • 18
  • 33
1

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

Community
  • 1
  • 1
Lars Nielsen
  • 150
  • 11