DatePickerDialog之后的setText使用本地日期格式

时间:2016-11-08 21:34:38

标签: android date locale date-formatting

在我的Android Studio项目中,我有一个DatePickerDialog。 在onDateSet上,我有3个参数:

  • int selectedYear;
  • int selectedMonth;
  • int selectedDay;

我想使用设备的本地格式制作一个setText。

例如,在美国,日期类似于: mm / dd / yyyy ,但在法国,它就像 dd-mm-yyyy

我该怎么做?

这是我的代码:

@Override
public void onClick(View view) {
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH);
    int day = cal.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog datePicker;
    datePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener(){
            @Override
            public void onDateSet(DatePicker datePicker, int selectYear, int selectedMonth, int selectedDay) {
                textViewDate.setText("HERE I HAVE TO PUT THE DATE WITH THE LOCAL FORMAT);
            }
        }, year, month, day);
        datePicker.show();
    }
});

由于

2 个答案:

答案 0 :(得分:0)

您可以使用以下方法:

public String formatDateStyles(Date date, Locale currentLocale) {

    String result = "";
    DateFormat formatter;

    int[] styles = { DateFormat.DEFAULT, DateFormat.SHORT, DateFormat.MEDIUM, DateFormat.LONG, DateFormat.FULL };

    for (int k = 0; k < styles.length; k++) {
      formatter = DateFormat.getDateInstance(styles[k], currentLocale);
      result = formatter.format(date);
    }

    return result;
  }

public Date getDate(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, day);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

通过这种方式:

textViewDate.setText(formatDateStyles(getDate(selectYear, selectedMonth, selectedDay), new Locale("en", "US")));

更多详情here

答案 1 :(得分:0)

试试这个:

myField     cooked
0000000009      0009
0000123456    123456
00ABCE1234  ABCE1234