我一直在尝试这个。很长一段时间 我今天有约会,我想把它与具体日期进行比较。
但是当我像这样设置特定日期时,它会给我错误的输出:
Calendar cal;
SimpleDateFormat dateformatter;
String currentdate;
cal = Calendar.getInstance();
dateformatter = new SimpleDateFormat("yyyy-MM-dd");
//Getting today's date
currentdate = dateformatter.format(cal.getTime());
Log.i(Class_Tag, "current = " + currentdate);
//Setting specific date
Date start = cal.getTime();
cal.set(2012, 06, 20);
Date end = cal.getTime();
Log.i(Class_Tag, "end = " + dateformatter.format(end));
long diff = end.getDate() - start.getDate();
Log.i(Class_Tag, "diff : " + diff);
long diff1 = end.getMonth() - start.getMonth();
Log.i(Class_Tag, "diff mnth : " + diff1);
long diff2 = end.getYear() - start.getYear();
Log.i(Class_Tag, "diff yr : " + diff2);
if (start.compareTo(end) == 0) {
Log.i(Class_Tag, "EQUAL");
} else if (start.compareTo(end) < 0) {
Log.i(Class_Tag, "end b4 start, delete");
} else {
Log.i(Class_Tag, "start b4 end, do nothing");
输出:
current = 2012-06-20
end = 2012-07-20 ////WHY it is showing month as '7' when I've set it to '6'?
diff : 0
diff mnth : 1 //Because of the wrong month in end date, this comes 1 instead of 0
diff yr : 0
end b4 start, delete //this also is not correct
我尝试了几种解决方案,但没有收获。
我唯一的目标是确定特定日期是否已过去今天的日期。
任何帮助表示感谢。
在以下代码段中,
//Setting specific date
Date start = cal.getTime();
cal.set(2012, 06, 20);
Date end = cal.getTime();
如果我将cal.set(2012, 06, 20);
设置为cal.set(2012, 05, 20);
,则为月份差异。来到0。
这意味着特定日期的month
增加了'1',但是 为什么 ?
答案 0 :(得分:2)
试试这个;
Calendar cal = Calendar.getInstance();
long dateNowMillis = cal.getTimeInMillis();
cal.set(2013, 1, 23);
long specDate = cal.getTimeInMillis();
if(dateNowMillis > specDate)
{
System.out.println("Passed");
}
else if(dateNowMillis == specDate)
{
System.out.println("Now");
}
else
{
System.out.println("Not passed");
}
答案 1 :(得分:1)
FYI, 一个月由0到11的整数表示; 0是1月,1是2月,依此类推;因此11月是12月。
您可以在此处详细了解Date,了解SimpleDateFormat。
<强>更新强>
关于 getMonth() =&gt;的另一件事已弃用,而不是Calendar.get(Calendar.MONTH)
,请检查here。
答案 2 :(得分:1)
@GAMA就像这样,你得到:
yourDate.setDate(yourDate.getDate() - daysToSubtract);
希望它有所帮助。