如何从Android DatePicker

时间:2015-11-27 19:27:58

标签: java android datetime datepicker

android DatePicker提供以下回调

public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
    }

如何提取以下内容:

  • int day获取文字日,如周五或周一或周二或周四
  • int month获取文字月份,例如Jan或Feb或Mar

所以基本上我想要得到两个不同的值,一天一个,然后一个月。

3 个答案:

答案 0 :(得分:2)

你可以试试这个:

public void onDateSet(DatePicker view, int year, int month, int day) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, day);

    SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM");
    String output = formatter.format(calendar.getTime()); //eg: "Tue May"
}

答案 1 :(得分:0)

使用SimpleDateFormat dateformat = new SimpleDateFormat(“dd / MMM / yyyy”);

放入int日历对象。 Calendar cal = Calendar.getInstance(); cal.set(Calendar.Date,day); cal.set(的Calendar.MONTH,月); cal.set(Calendar.Year,年); StringformatedDate = dateFormat.format(cal.getTime());

答案 2 :(得分:0)

在你的回调听众课程中,应用SimpleDateFormat来获取日期和月份作为文本 - 例如如下:

Calendar now = Calendar.getInstance();

DatePicker datePicker = ... // e.g. (DatePicker) fragmentView.findViewById(R.id.datePicker);
datePicker.init(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH),
    new DatePicker.OnDateChangedListener() {
        final SimpleDateFormat mDayFormat = new SimpleDateFormat("EEE", Locale.US);
        final SimpleDateFormat mMonthFormat = new SimpleDateFormat("MMM", Locale.US);

        @Override
        public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Calendar cal = Calendar.getInstance();
            cal.set(year, monthOfYear, dayOfMonth);

            String day = mDayFormat.format(cal.getTime());
            String month = mMonthFormat.format(cal.getTime());

            // ... Do stuff with 'day', 'month'.
        }
    });

您还可以通过以下方式初始化格式来获取日,月(例如星期五,11月)的完整代表:

final SimpleDateFormat mDayFormat = new SimpleDateFormat("EEEE", Locale.US);
final SimpleDateFormat mMonthFormat = new SimpleDateFormat("MMMM", Locale.US);