检查日期与今天的日期
问题描述:
我已经写了一些代码来检查两个日期,一个开始日期和一个结束日期。如果结束日期在开始日期之前,它将提示说结束日期是在开始日期之前。
I have written some code to check two dates, a start date and an end date. If the end date is before the start date, it will give a prompt that says End date is before start date.
我还想添加一个检查,如果开始日期是在今天之前(今天在用户使用应用程序的那一天),我该怎么做? (下面的日期检查代码,所有这些都是为android编写的,如果有任何方向)
I also want to add a check for if the start date is before today (today as in the day of which the user uses the application) How would I do this? ( Date checker code below, also all this is written for android if that has any bearing)
if(startYear > endYear)
{
fill = fill + 1;
message = message + "End Date is Before Start Date" + "\n";
}
else if(startMonth > endMonth && startYear >= endYear)
{
fill = fill + 1;
message = message + "End Date is Before Start Date" + "\n";
}
else if(startDay > endDay && startMonth >= endMonth && startYear >= endYear)
{
fill = fill + 1;
message = message + "End Date is Before Start Date" + "\n";
}
答
这是否有帮助? p>
Does this help?
Calendar c = Calendar.getInstance();
// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
// and get that as a Date
Date today = c.getTime();
// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();
// user-specified date which you are testing
// let's say the components come from a form or something
int year = 2011;
int month = 5;
int dayOfMonth = 20;
// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
// and get that as a Date
Date dateSpecified = c.getTime();
// test your condition
if (dateSpecified.before(today)) {
System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
} else {
System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");
}