简体   繁体   中英

Joda & Android: How to format a date for display in the user's locale?

I am using the Joda library. My requirement is that the displayed date string is appropriate for the user's locale, ie on a german device 12.12.2014 and on a american device 2014/12/12. I found that I can use the toString() Method of LocalDate.

LocalDate localDate = LocalDate.now();
localDate.toString("yyyy/MM/dd", Locale.getDefault());

If I understand right, I need to supply a pattern, but IMHO this defeats the purpose of specifying a locale.

Can anybody enlighten me?

My solution, which will format the displayed date appropriate for the device's locale:

        DateTimeFormatter fmt = DateTimeFormat.mediumDate();
        String str = fmt.print(localDate);
        getGeburtsdatumEditText().setText(str);

I use this code for similar case for generate hours and minutes:

public String timeGenerateString( int iHour, int iMinute) {
  if( (iHour   < 0) || (iHour   > 24))  return "";
  if( (iMinute < 0) || (iMinute > 59))  return "";

  if( android.text.format.DateFormat.is24HourFormat( getApplicationContext()) == true)
    return  "" + String.format("%02d", iHour) + ":" + String.format("%02d", iMinute);
   else
    if( iHour >= 13)
      return  "" + String.format("%02d", (iHour - 12)) + ":" + String.format("%02d", iMinute) + " PM";
     else
      return  "" + String.format("%02d", iHour) + ":" + String.format("%02d", iMinute) + " AM";
}

May be this will be usually for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM