我是Android编程的新手,目前正在开发一个应用程序。如果在7天内,有人可以帮助我确认用户输入的日期吗?
因此,我有两个字符串“ startDay”和“ endDay”,用户在其中输入
startDay = 1/2/2017
endDay = 6/2/2017
然后继续下一步。如果用户输入
startDay = 1/2/2017
endDay = 9/2/2017,然后返回消息“最长7天”
有我做的代码
@Override
public void onClick(View v) {
if (v==btnSearch){
String startDaystr = startDay.getText().toString();
String startMonthtstr = startMonth.getText().toString();
String endDaystr = endDay.getText().toString();
String endMonthstr = endMonth.getText().toString();
String endYearstr = endYear.getText().toString();
if(Integer.valueOf(startDaystr) >1 && Integer.valueOf(endDaystr) < 8){
sharedPreferenceCustom = SharedPreferenceCustom.getInstance(getContext());
sharedPreferenceCustom.putSharedPref("startDay", startDaystr);
sharedPreferenceCustom.putSharedPref("startMonth",startMonthtstr);
sharedPreferenceCustom.putSharedPref("endDay",endDaystr);
sharedPreferenceCustom.putSharedPref("endMonth",endMonthstr);
sharedPreferenceCustom.putSharedPref("endYear",endYearstr);
startActivity(new Intent(getActivity(), activity_history.class));
}else{
Toast.makeText(getActivity(), "Maximum 7 days!", Toast.LENGTH_LONG).show();
}
}
}
但是当我输入
startDay = 22/2/2017
endDay = 25/2/2017
结果是“最多7天”,应返回到下一步
请帮助我..im搜索并尝试过但未获得这样的解决方案。
最佳答案
我添加了startYearStr
,请注意。
使用以下代码:
String startDaystr = startDay.getText().toString();
String startMonthtstr = startMonth.getText().toString();
String startYearstr = startYear.getText().toString();
String endDaystr = endDay.getText().toString();
String endMonthstr = endMonth.getText().toString();
String endYearstr = endYear.getText().toString();
Calendar startDate = Calendar.getInstance();
startDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(startDaystr));
startDate.set(Calendar.MONTH, Integer.parseInt(startMonthtstr));
startDate.set(Calendar.YEAR, Integer.parseInt(startYearstr));
startDate.set(Calendar.HOUR_OF_DAY, 0);
startDate.set(Calendar.MINUTE, 0);
startDate.set(Calendar.SECOND, 0);
Calendar endDate = Calendar.getInstance();
endDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(endDaystr));
endDate.set(Calendar.MONTH, Integer.parseInt(endMonthstr));
endDate.set(Calendar.YEAR, Integer.parseInt(endYearstr));
endDate.set(Calendar.HOUR_OF_DAY, 0);
endDate.set(Calendar.MINUTE, 0);
endDate.set(Calendar.SECOND, 0);
long diff = endDate.getTimeInMillis() - startDate.getTimeInMillis();
long dayCount = diff / (24 * 60 * 60 * 1000);
dayCount
为您提供两个日期之间的日期差。