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
所以基本上我想得到两个不同的值,一天自己,然后一个月自己。
你可以试试这个:
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"
}
在回调侦听器类中,应用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'.
}
});
您还可以通过以下方式初始化格式来获得日期、月份(例如,星期五、十一月)的完整表示:
final SimpleDateFormat mDayFormat = new SimpleDateFormat("EEEE", Locale.US);
final SimpleDateFormat mMonthFormat = new SimpleDateFormat("MMMM", Locale.US);
使用
SimpleDateFormat dateformat=new SimpleDateFormat("dd/MMM/yyyy");
放入日历对象。
Calendar cal=Calendar.getInstance();
cal.set(Calendar.Date,day);
cal.set(Calendar.Month,month);
cal.set(Calendar.Year,year);
StringformatedDate=dateFormat.format(cal.getTime());