gpt4 book ai didi

java - 如何验证android中的范围?

转载 作者:行者123 更新时间:2023-12-01 08:53:51 25 4
gpt4 key购买 nike

我是 Android 编程新手,目前正在开发一个应用程序。有人可以帮助我如何验证用户输入的日期是否在 7 天范围内吗?所以,我有两个字符串“startDay”和“endDay”,其中用户输入开始日 = 1/2/2017结束日 = 2017 年 6 月 2 日

然后继续下一步。如果用户输入开始日 = 1/2/2017endDay = 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();
}



}
}

但是当我输入时开始日 = 22/2/2017结束日期 = 25/2/2017

结果是“最长 7 天”,应该返回到下一步

请帮助我..我也搜索并尝试过,但没有得到这样的解决方案..

最佳答案

我添加了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 给出两个日期之间的天数差异。

关于java - 如何验证android中的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42183699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com