我想在我的应用程序中比较两个日期
第一个日期将是今天的日期 第二个将来自数据库
要保存第二个日期,我的代码如下; (为了简单起见,使用了明天的日期)
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String tomorrowAsString = dateFormat.format(tomorrow);
所以 tomorrowAsString (10-Oct-2015)
存储在我数据库的表中
在另一种形式中,我正在检索该日期并将其放入一个字符串中
String steepingDate = (c.getString(3));
我想我需要将该字符串转换为日期格式,然后使用以下内容获取今天的日期;
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String todayAsString = dateFormat.format(today);
这是我卡住的地方,因为我不确定如何将 steepingDate
转换为 Date
然后比较字符串的实际方法是什么,我尝试过在线查看,但我尝试过很多不同的方法,但到目前为止都没有奏效。我想知道这两个中哪个更磨碎
编辑:
我结合了一些答案并得出以下结论;
do {
String steepingDate = (c.getString(3));
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date steepingdate = formatter.parse(steepingDate);
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
if(today.compareTo(steepingdate)>0)
{
CompleteSteeping.add(c.getString(1));
}
i += 1;
}while (c.moveToNext());
然而上;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date steepingdate = formatter.parse(steepingDate);
我收到一个错误说明
'无法解析的日期:“java.util.GregorianCalender[time=1444461352665,areFieldsSet=true,Ienient=true\zone=GMT,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=9, WEEK_OF_YEAR=41,WEEK_OF_MONTH=2,DAY_OF_MONTH=10,DAY_OF_YEAR=283,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=2,AM_PM=0,HOUR=7,HOUR_OF_DAY=7,MINUTE=15,SECOND=52,MILLISE_OFFSET5,ZONDONE=66 0DST_OFFSET=0]"(在偏移量 0 处)
最佳答案
如果你只是想比较字符串,它看起来像这样:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String tomorrowAsString = dateFormat.format(tomorrow);
calendar = Calendar.getInstance();
Date today = calendar.getTime();
String todayAsString = dateFormat.format(today);
if(tomorrowAsString.equals(todayAsString))
System.out.println(true);
else
System.out.println(false);
关于Android - 比较两个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33032762/