سؤال

I am creating an Android application. I have a GregorianCalendar variable. I want to get the date from this variable as MM-dd-yyyy if the locale is US or dd-MM-yyyy if the locale is EU and so on. I don't want to hard code each locale string, I want to make it depend on the phone's locale.

The problem is that after looking through tens of similar questions, I still couldn't get this to work. I am guessing it's two or three lines of code, perhaps using SimpleDateFormat or GregorianCalendar.get() or getDisplayName().

Thanks for the help.

هل كانت مفيدة؟

المحلول

try this

    GregorianCalendar gc = ...
    String str = DateFormat.getDateInstance(DateFormat.SHORT).format(gc.getTime());

BTW default date format (SHORT) for US is dd/MM/yy eg 30/05/13

نصائح أخرى

Did you try this

DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, yourLocale);
String formattedDate = df.format(yourcalender.getTime());

with yourcalender is GregorianCalendar variable

Better yet why not use the user's own preferred date format? Locale.getLocale() returns the user's preferred locale, you can use this to format all your localised values (dates, times, currency etc) and know that you're giving the user a format that they chose.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top