我正在使用两个函数来比较日期值,我将在其中检查start date是否大于/晚于end date。
第一个函数用于获取字符串值并使用该字符串值来初始化Calendar
:
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;
}
第二个函数用于比较 startDate 和 endDate(它们都是按钮):
public void compareDates(String startDate, String endDate){
Calendar startCheckDate = Calendar.getInstance();
int startmm = getFromCalendar(monitoringDate.getText().toString(), Calendar.MONTH);
int startyy = getFromCalendar(monitoringDate.getText().toString(), Calendar.YEAR);
int startdd = getFromCalendar(monitoringDate.getText().toString(), Calendar.DAY_OF_MONTH);
startCheckDate.set(startyy, startmm, startdd);
Calendar endCheckDate = Calendar.getInstance();
int endmm = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.MONTH);
int endyy = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.YEAR);
int enddd = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.DAY_OF_MONTH);
endCheckDate.set(endyy, endmm, enddd);
if(endCheckDate.after(startCheckDate)){
Toast.makeText(getSherlockActivity(), "End date cannot be smaller than start date", Toast.LENGTH_SHORT).show();
}
}
由于某种原因,该compareDates
功能根本不起作用。请帮忙