我想在我的应用程序中比较两个日期
第一个日期将是今天的日期.第二个日期将来自数据库
要保存第二个日期,我的代码如下; (使用明天约会以保持简单)
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);
Run Code Online (Sandbox Code Playgroud)
因此tomorrowAsString (10-Oct-2015)存储在我的数据库中的表中
在另一种形式中,我正在检索该日期并将其放入String中
String steepingDate = (c.getString(3));
Run Code Online (Sandbox Code Playgroud)
我想我需要将该字符串转换为日期格式,然后使用以下内容获取今天的日期;
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String todayAsString = dateFormat.format(today);
Run Code Online (Sandbox Code Playgroud)
这里是我卡住因为我不知道如何打开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());
Run Code Online (Sandbox Code Playgroud)
但是;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date steepingdate = formatter.parse(steepingDate);
Run Code Online (Sandbox Code Playgroud)
我收到一个错误说明
"无法解析日期:"java.util.GregorianCalender [时间= 1444461352665,areFieldsSet =真,Ienient =真\区= 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,微差= 665,ZONE_OFFSET = 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);
Run Code Online (Sandbox Code Playgroud)