我有以下功能:
public String splitDate(String data, int i){
String[] items = data.split("/");
for(String item:items){
return items[i];
}
return null;
}
这需要date string
这样的“12/24/2013”并将其拆分。
使用此函数我试图以特定顺序实例化我的datePicker:
public Dialog onCreateDialog(Bundle savedInstanceState) {
int yy = 0;
int dd = 0;
int mm = 0;
if(dateString.length()>1){
yy = Integer.parseInt(splitDate(dateString,2);
dd = Integer.parseInt(splitDate(dateString,1);
mm = Integer.parseInt(splitDate(dateString,0);
}else{
final Calendar calendar = Calendar.getInstance();
yy = calendar.get(Calendar.YEAR);
mm = calendar.get(Calendar.MONTH);
dd = calendar.get(Calendar.DAY_OF_MONTH);
}
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
但是使用这个函数我得到以下错误:
08-27 00:14:39.383: E/AndroidRuntime(16368): FATAL EXCEPTION: main
08-27 00:14:39.383: E/AndroidRuntime(16368): java.lang.IllegalArgumentException: current should be >= start and <= end
有人帮忙吗?如何让String dateString
填充日期选择器?
答案 0 :(得分:1)
您可以使用简单的日期格式从字符串中获取信息,这是一个简单的函数,可以解析您的日期并返回必填字段:
private int getFromCalendar(String strDate,int field)
{
int result = -1;
try
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");// this is your date format "12/24/2013" = "MM/dd/yyy"
java.util.Date date = formatter.parse(strDate);//convert to date
Calendar cal = Calendar.getInstance();// get calendar instance
cal.setTime(date);//set the calendar date to your date
result = cal.get(field); // get the required field
return result;//return the result.
}
catch (ParseException e)
{
e.printStackTrace();
}
return result;
}
这就是你打电话的方式:
int yy = getFromCalendar("12/24/2013",Calendar.YEAR);
int mm = getFromCalendar("12/24/2013",Calendar.MONTH);
int dd = getFromCalendar("12/24/2013",Calendar.DAY_OF_MONTH);