我想从字符串中解析日期并在DatePickerDialog中设置它:
try {
myCalendar.setTime(mySimpleFormatter.parse(jsonObj.getString("dob")));
} catch (ParseException e) {
System.out.println("!!!");
}
myEditBox.setText(mySimpleFormatter.format(myCalendar.getTime()));
myDatePickerDialog.getDatePicker().updateDate(myCalendar.getTime().getYear()); // depricated
但问题是不推荐使用myCalendar.getTime()。getYear(),getMonth(),getDay。那应该用什么?
答案 0 :(得分:2)
Date.getYear(), getMonth() and getDay()
已弃用,并特别要求您使用Calendar.get()
以下是API文档中的相关说明
已过时。自JDK version 1.1,
替换为Calendar.get(Calendar.YEAR) - 1900。
http://download.oracle.com/javase/6/docs/api/java/util/Date.html#getYear%28%29
我使用过这段代码:
private void setDateTimeField(){
usereditbirthdateedittext.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
usereditbirthdateedittext.setText(dateFormatter.format(newDate.getTime()));
selectedDate = new Date(newDate.getTimeInMillis());
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
答案 1 :(得分:1)
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
int day= cal.get(Calendar.DAY_OF_MONTH);
答案 2 :(得分:0)
您实际上是在Date上调用方法,这些方法已被弃用。 (myCalendar.getDate()返回Date对象)。
在Calendar的实例上,您可以使用get()并传递常量来获取年,月,日等等(请参阅get()的链接文档。)
答案 3 :(得分:-1)
我建议您使用JodaTime,因为它功能更强大,可以解决所有与日期相关的问题。
以下是示例示例:
DateTimeFormatter fromFormat = DateTimeFormat.forPattern("dd/MM/yyyy"); // String pattern of your DOB from which you want to create DateTime Object
DateTime dob = fromFormat.parseDateTime(jsonObj.getString("dob")); // This will give you DateTime Object
DateTimeFormatter toFormat = DateTimeFormat.forPattern("MMMM dd, yyyy"); // String pattern of your parsed DOB
myEditBox.setText(dob.toString(toFormat)); // April 2, 2016
myDatePickerDialog.getDatePicker().updateDate(dob.getYear());