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 the end date is before start date.
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";
}
Don't complicate it that much. Use this easy way. Import DateUtils java class and call the following methods which returns a boolean.
DateUtils.isSameDay(date1,date2);
DateUtils.isSameDay(calender1,calender2);
DateUtils.isToday(date1);
For more info refer this article DateUtils Java
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 + "]");
}
LocalDate
.parse( "2021-01-23" )
.isBefore(
LocalDate.now(
ZoneId.of( "Africa/Tunis" )
)
)
… or:
try
{
org.threeten.extra.LocalDateRange range =
LocalDateRange.of(
LocalDate.of( "2021-01-23" ) ,
LocalDate.of( "2021-02-21" )
)
;
if( range.isAfter(
LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
) { … }
else { … handle today being within or after the range. }
} catch ( java.time.DateTimeException e ) {
// Handle error where end is before start.
}
The other answers ignore the crucial issue of time zone .
The other answers use outmoded classes.
The old date-time classes bundled with the earliest versions of Java are poorly designed, confusing, and troublesome. Avoid java.util.Date/.Calendar and related classes.
LocalDate
For date-only values, without time-of-day and without time zone, use the LocalDate
class.
LocalDate start = LocalDate.of( 2016 , 1 , 1 );
LocalDate stop = start.plusWeeks( 1 );
Be aware that while LocalDate
does not store a time zone, determining a date such as “today” requires a time zone. For any given moment, the date may vary around the world by time zone. For example, a new day dawns earlier in Paris than in Montréal. A moment after midnight in Paris is still “yesterday” in Montréal.
If all you have is an offset-from-UTC , use ZoneOffset
. If you have a full time zone (continent/region), then use ZoneId
. If you want UTC, use the handy constant ZoneOffset.UTC
.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
Comparing is easy with isEqual
, isBefore
, and isAfter
methods.
boolean invalidInterval = stop.isBefore( start );
We can check to see if today is contained within this date range. In my logic shown here I use the Half-Open approach where the beginning is inclusive while the ending is exclusive . This approach is common in date-time work. So, for example, a week runs from a Monday going up to but not including the following Monday.
// Is today equal or after start (not before) AND today is before stop.
boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ) ;
LocalDateRange
If working extensively with such spans of time, consider adding the ThreeTen-Extra library to your project. This library extends the java.time framework, and is the proving ground for possible additions to java.time.
ThreeTen-Extra includes an LocalDateRange
class with handy methods such as abuts
, contains
, encloses
, overlaps
, and so on.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.
To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
Android already has a dedicated class for this. Check DateUtils.isToday(long when)
Using pure Java:
public static boolean isToday(Date date){
Calendar today = Calendar.getInstance();
Calendar specifiedDate = Calendar.getInstance();
specifiedDate.setTime(date);
return today.get(Calendar.DAY_OF_MONTH) == specifiedDate.get(Calendar.DAY_OF_MONTH)
&& today.get(Calendar.MONTH) == specifiedDate.get(Calendar.MONTH)
&& today.get(Calendar.YEAR) == specifiedDate.get(Calendar.YEAR);
}
Using Joda Time this can be simplified to:
DateMidnight startDate = new DateMidnight(startYear, startMonth, startDay);
if (startDate.isBeforeNow())
{
// startDate is before now
// do something...
}
to check if a date is today's date or not only check for dates not time included with that so make time 00:00:00 and use the code below
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);
Date today = c.getTime();
// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();
int dayOfMonth = 24;
int month = 4;
int year =2013;
// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month - 1);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
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 dateSpecified = c.getTime();
// test your condition
if (dateSpecified.before(today)) {
Log.v(" date is previou")
} else if (dateSpecified.equal(today)) {
Log.v(" date is today ")
}
else if (dateSpecified.after(today)) {
Log.v(" date is future date ")
}
Hope it will help....
boolean isBeforeToday(Date d) {
Date today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
return d.before(today);
}
another way to do this operation:
public class TimeUtils {
/**
* @param timestamp
* @return
*/
public static boolean isToday(long timestamp) {
Calendar now = Calendar.getInstance();
Calendar timeToCheck = Calendar.getInstance();
timeToCheck.setTimeInMillis(timestamp);
return (now.get(Calendar.YEAR) == timeToCheck.get(Calendar.YEAR)
&& now.get(Calendar.DAY_OF_YEAR) == timeToCheck.get(Calendar.DAY_OF_YEAR));
}
}
I assume you are using integers to represent your year, month, and day? If you want to remain consistent, use the Date methods.
Calendar cal = new Calendar();
int currentYear, currentMonth, currentDay;
currentYear = cal.get(Calendar.YEAR);
currentMonth = cal.get(Calendar.MONTH);
currentDay = cal.get(Calendar.DAY_OF_WEEK);
if(startYear < currentYear)
{
message = message + "Start Date is Before Today" + "\n";
}
else if(startMonth < currentMonth && startYear <= currentYear)
{
message = message + "Start Date is Before Today" + "\n";
}
else if(startDay < currentDay && startMonth <= currentMonth && startYear <= currentYear)
{
message = message + "Start Date is Before Today" + "\n";
}
Try this:
public static boolean isToday(Date date)
{
return org.apache.commons.lang3.time.DateUtils.isSameDay(Calendar.getInstance().getTime(),date);
}
public static boolean itIsToday(long date){
boolean result = false;
try{
Calendar calendarData = Calendar.getInstance();
calendarData.setTimeInMillis(date);
calendarData.set(Calendar.HOUR_OF_DAY, 0);
calendarData.set(Calendar.MINUTE, 0);
calendarData.set(Calendar.SECOND, 0);
calendarData.set(Calendar.MILLISECOND, 0);
Calendar calendarToday = Calendar.getInstance();
calendarToday.setTimeInMillis(System.currentTimeMillis());
calendarToday.set(Calendar.HOUR_OF_DAY, 0);
calendarToday.set(Calendar.MINUTE, 0);
calendarToday.set(Calendar.SECOND, 0);
calendarToday.set(Calendar.MILLISECOND, 0);
if(calendarToday.getTimeInMillis() == calendarData.getTimeInMillis()) {
result = true;
}
}catch (Exception exception){
Log.e(TAG, exception);
}
return result;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.