我正在制作一个应用程序,我要求用户从时间选择器中选择一个时间。获取时间选择器的代码工作正常。我以字符串格式获取时间,如“18:24”。现在我想要什么如果用户选择 future 的时间,那么应该举杯 toast 。 例如
User Selected time from time picker="18:40"
Current Time="18:50"
then toast should be displayed
但这并没有发生
代码
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
Calendar c=Calendar.getInstance();
Date currentTime;
String time = data.getStringExtra("TIME");
SimpleDateFormat sdf=new SimpleDateFormat("kk:mm");
try {
Date timeCompare=sdf.parse(time);
currentTime=c.getTime();
if(timeCompare.compareTo(currentTime)==0){
etStartTime.setText(time);
}else{
Toast.makeText(mContext, "Your cannot select future time", Toast.LENGTH_SHORT).show();
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
最佳答案
行内代码:
Date timeCompare=sdf.parse(time);
将返回 1970 年的日期
同时代码行:
currentTime=c.getTime();
将返回 2014 年的当前日期
所以代码:
if (timeCompare.compareTo(currentTime)==0)
永远不会执行,因为 campare 等于 (-1 == 0)
这是一个测试代码(我在 Button 上创建的作为调试技术,而不是使用您的代码将其记录到 logcat):
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar c=Calendar.getInstance();
Date currentTime;
String time = "23:00";
SimpleDateFormat sdf=new SimpleDateFormat("kk:mm");
try {
Date timeCompare=sdf.parse(time);
Log.e("TEST_TAG", "timeCompare is: "+ timeCompare.toString());
currentTime=c.getTime();
Log.e("TEST_TAG","currentTime is: "+ currentTime.toString());
Log.e("TEST_TAG", "compareTo result is: " + String.valueOf(timeCompare.compareTo(currentTime)) );
if(timeCompare.compareTo(currentTime)==0){
// setStartTime.setText(time);
}else{
Toast.makeText(getApplicationContext(), "Your cannot select future time", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
logcat 结果是:
11-14 16:18:02.618: E/TEST_TAG(2137): timeCompare is: Thu Jan 01 23:00:00 EET 1970
11-14 16:18:02.618: E/TEST_TAG(2137): currentTime is: Fri Nov 14 16:18:02 EET 2014
11-14 16:18:02.618: E/TEST_TAG(2137): compareTo result is: -1
为了纠正这个问题,我建议将数据 Bandle 中的时间保存为全长,如“yyyy-MM-dd HH:mm:ss” 然后使用 SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 如下,这样您的代码将正确运行。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date timeCompare = sdf.parse(time);
Date currentTime = new Date();
int comareResult = timeCompare.compareTo(currentTime);
if (comareResult = 0){
...
}
关于android - 比较android中的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26931080/