Related
I have to use the Java Date class for this problem (it interfaces with something out of my control).
How do I get the start and end date of a year and then iterate through each date?
java.time
Using java.time library built into Java 8 and later. Specifically the LocalDate and TemporalAdjusters classes.
import java.time.LocalDate
import static java.time.temporal.TemporalAdjusters.firstDayOfYear
import static java.time.temporal.TemporalAdjusters.lastDayOfYear
LocalDate now = LocalDate.now(); // 2015-11-23
LocalDate firstDay = now.with(firstDayOfYear()); // 2015-01-01
LocalDate lastDay = now.with(lastDayOfYear()); // 2015-12-31
If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like
lastDay.atStartOfDay(); // 2015-12-31T00:00
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_YEAR, 1);
Date start = cal.getTime();
//set date to last day of 2014
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 11); // 11 = december
cal.set(Calendar.DAY_OF_MONTH, 31); // new years eve
Date end = cal.getTime();
//Iterate through the two dates
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(start);
while (gcal.getTime().before(end)) {
gcal.add(Calendar.DAY_OF_YEAR, 1);
//Do Something ...
}
// suppose that I have the following variable as input
int year=2011;
Calendar calendarStart=Calendar.getInstance();
calendarStart.set(Calendar.YEAR,year);
calendarStart.set(Calendar.MONTH,0);
calendarStart.set(Calendar.DAY_OF_MONTH,1);
// returning the first date
Date startDate=calendarStart.getTime();
Calendar calendarEnd=Calendar.getInstance();
calendarEnd.set(Calendar.YEAR,year);
calendarEnd.set(Calendar.MONTH,11);
calendarEnd.set(Calendar.DAY_OF_MONTH,31);
// returning the last date
Date endDate=calendarEnd.getTime();
To iterate, you should use the calendar object and increment the day_of_month variable
Hope that it can help
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_YEAR, 1);
System.out.println(cal.getTime().toString());
cal.set(Calendar.DAY_OF_YEAR, 366); // for leap years
System.out.println(cal.getTime().toString());
An improvement over Srini's answer.
Determine the last date of the year using Calendar.getActualMaximum.
Calendar cal = Calendar.getInstance();
calDate.set(Calendar.DAY_OF_YEAR, 1);
Date yearStartDate = calDate.getTime();
calDate.set(Calendar.DAY_OF_YEAR, calDate.getActualMaximum(Calendar.DAY_OF_YEAR));
Date yearEndDate = calDate.getTime();
If you are looking for a one-line-expression, I usually use this:
new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(new java.util.Date().getYear())+"-01-01")
I assume that you have Date class instance and you need to find first date and last date of the current year in terms of Date class instance. You can use the Calendar class for this. Construct Calendar instance using provided date class instance. Set the MONTH and DAY_OF_MONTH field to 0 and 1 respectively, then use getTime() method which will return Date class instance representing first day of year. You can use same technique to find end of year.
Date date = new Date();
System.out.println("date: "+date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println("cal:"+cal.getTime());
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("cal new: "+cal.getTime());
Update: The Joda-Time library is now in maintenance mode with its team advising migration to the java.time classes. See the correct java.time Answer by Przemek.
Time Zone
The other Answers ignore the crucial issue of time zone.
Joda-Time
Avoid doing date-time work with the notoriously troublesome java.util.Date class. Instead use either Joda-Time or java.time. Convert to j.u.Date objects as needed for interoperability.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ;
int year = 2015 ;
DateTime firstOfYear = new DateTime( year , DateTimeConstants.JANUARY , 1 , 0 , 0 , zone ) ;
DateTime firstOfNextYear = firstOfYear.plusYears( 1 ) ;
DateTime firstMomentOfLastDayOfYear = firstOfNextYear.minusDays( 1 ) ;
Convert To java.util.Date
Convert to j.u.Date as needed.
java.util.Date d = firstOfYear.toDate() ;
You can use Jodatime as shown in this thread Java Joda Time - Implement a Date range iterator
Also, you can use gregorian calendar and move one day at a time, as shown here. I need a cycle which iterates through dates interval
PS. Piece of advice: search it first.
You can use the apache commons-lang project which has a DateUtils class.
They provide an iterator which you can give the Date object.
But I highly suggest using the Calendar class as suggested by the other answers.
First and Last day of Year
import java.util.Calendar
import java.text.SimpleDateFormat
val parsedDateInt = new SimpleDateFormat("yyyy-MM-dd")
val cal2 = Calendar.getInstance()
cal2.add(Calendar.MONTH, -(cal2.get(Calendar.MONTH)))
cal2.set(Calendar.DATE, 1)
val firstDayOfYear = parsedDateInt.format(cal2.getTime)
cal2.add(Calendar.MONTH, (11-(cal2.get(Calendar.MONTH))))
cal2.set(Calendar.DATE, cal2.getActualMaximum(Calendar.DAY_OF_MONTH))
val lastDayOfYear = parsedDateInt.format(cal2.getTime)
val instance = Calendar.getInstance()
instance.add(Calendar.YEAR,-1)
val prevYear = SimpleDateFormat("yyyy").format(DateTime(instance.timeInMillis).toDate())
val firstDayPreviousYear = DateTime(prevYear.toInt(), 1, 1, 0, 0, 0, 0)
val lastDayPreviousYear = DateTime(prevYear.toInt(), 12, 31, 0, 0, 0, 0)
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(start);
while (gcal.getTime().before(end)) {
gcal.add(Calendar.DAY_OF_YEAR, 1);
//Do Something ...
}
The GregorianCalendar creation here is pointless. In fact, going through Calendar.java source code shows that Calendar.getInstance() already gives a GregorianCalendar instance.
Regards,
Nicolas
Calendar cal = Calendar.getInstance();//getting the instance of the Calendar using the factory method
we have a get() method to get the specified field of the calendar i.e year
int year=cal.get(Calendar.YEAR);//for example we get 2013 here
cal.set(year, 0, 1); setting the date using the set method that all parameters like year ,month and day
Here we have given the month as 0 i.e Jan as the month start 0 - 11 and day as 1 as the days starts from 1 to30.
Date firstdate=cal.getTime();//here we will get the first day of the year
cal.set(year,11,31);//same way as the above we set the end date of the year
Date lastdate=cal.getTime();//here we will get the last day of the year
System.out.print("the firstdate and lastdate here\n");
java.time.YearMonth
How to Get First Date and Last Date For Specific Year and Month.
Here is code using YearMonth Class.
YearMonth is a final class in java.time package, introduced in Java 8.
public static void main(String[] args) {
int year = 2021; // you can pass any value of year Like 2020,2021...
int month = 6; // you can pass any value of month Like 1,2,3...
YearMonth yearMonth = YearMonth.of( year, month );
LocalDate firstOfMonth = yearMonth.atDay( 1 );
LocalDate lastOfMonth = yearMonth.atEndOfMonth();
System.out.println(firstOfMonth);
System.out.println(lastOfMonth);
}
See this code run live at IdeOne.com.
2021-06-01
2021-06-30
I'm having some problem with calculate days between two dateFields. I already tried
`
DateField dateStart = new DateField();
DateField dateEnd = new DateField();
DateTime start = new DateTime(dateStart);
DateTime end = new DateTime(dateEnd);
int days = Days.daysBetween(new DateTime(start), new DateTime(end)).getDays();
`
Here is the error that I get after run this code
java.lang.IllegalArgumentException: No instant converter found for type: com.vaadin.ui.DateField
I also already tried using ChronoUnit
LocalDate startDate = LocalDate.now().minusDays(1);
LocalDate endDate = LocalDate.now();
long days = Period.between(startDate, endDate).getDays();
assertEquals(1, days);
long days2 = ChronoUnit.DAYS.between(startDate, endDate);
assertEquals(1, days2);
and also JudoTime
DateTime startDate = new DateTime().minusDays(1);
DateTime endDate = new DateTime();
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
Both code I get NullPointerException error. Is there any way that I can get number of days.
The other answers show how to calculate the difference between two dates in days using Java 8. But your actual problem is how to get the dates from Vaadin DateField (as p.streef and Ramachandran G A pointed out in the comments). Use dateStart.getValue() for that which will return a java.util.Date and can be passed to new DateTime().
This is simplest way to find the intermediate date values using java 8.
LocalDate startDate = LocalDate.now().minusDays(1);
LocalDate endDate = LocalDate.now();
long days = Period.between(startDate, endDate).getDays();
System.out.println(days);
The following snippet works. One of the reason for no instant converter error that you see is what time of the day do you want the day to be at. I mentioned start of day here. Interesting read here (How to convert Joda Localdate to Joda DateTime?) .
LocalDateTime startDateTime = LocalDate.now().atStartOfDay().minusDays(1);
LocalDateTime endDateTime = LocalDate.now().atStartOfDay();
long days = Period.between(startDateTime.toLocalDate(), endDateTime.toLocalDate()).getDays();
System.out.println("The difference in dates is " + days);
At the output : The difference in dates is 1
I have to use the Java Date class for this problem (it interfaces with something out of my control).
How do I get the start and end date of a year and then iterate through each date?
java.time
Using java.time library built into Java 8 and later. Specifically the LocalDate and TemporalAdjusters classes.
import java.time.LocalDate
import static java.time.temporal.TemporalAdjusters.firstDayOfYear
import static java.time.temporal.TemporalAdjusters.lastDayOfYear
LocalDate now = LocalDate.now(); // 2015-11-23
LocalDate firstDay = now.with(firstDayOfYear()); // 2015-01-01
LocalDate lastDay = now.with(lastDayOfYear()); // 2015-12-31
If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like
lastDay.atStartOfDay(); // 2015-12-31T00:00
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_YEAR, 1);
Date start = cal.getTime();
//set date to last day of 2014
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 11); // 11 = december
cal.set(Calendar.DAY_OF_MONTH, 31); // new years eve
Date end = cal.getTime();
//Iterate through the two dates
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(start);
while (gcal.getTime().before(end)) {
gcal.add(Calendar.DAY_OF_YEAR, 1);
//Do Something ...
}
// suppose that I have the following variable as input
int year=2011;
Calendar calendarStart=Calendar.getInstance();
calendarStart.set(Calendar.YEAR,year);
calendarStart.set(Calendar.MONTH,0);
calendarStart.set(Calendar.DAY_OF_MONTH,1);
// returning the first date
Date startDate=calendarStart.getTime();
Calendar calendarEnd=Calendar.getInstance();
calendarEnd.set(Calendar.YEAR,year);
calendarEnd.set(Calendar.MONTH,11);
calendarEnd.set(Calendar.DAY_OF_MONTH,31);
// returning the last date
Date endDate=calendarEnd.getTime();
To iterate, you should use the calendar object and increment the day_of_month variable
Hope that it can help
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_YEAR, 1);
System.out.println(cal.getTime().toString());
cal.set(Calendar.DAY_OF_YEAR, 366); // for leap years
System.out.println(cal.getTime().toString());
An improvement over Srini's answer.
Determine the last date of the year using Calendar.getActualMaximum.
Calendar cal = Calendar.getInstance();
calDate.set(Calendar.DAY_OF_YEAR, 1);
Date yearStartDate = calDate.getTime();
calDate.set(Calendar.DAY_OF_YEAR, calDate.getActualMaximum(Calendar.DAY_OF_YEAR));
Date yearEndDate = calDate.getTime();
If you are looking for a one-line-expression, I usually use this:
new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(new java.util.Date().getYear())+"-01-01")
I assume that you have Date class instance and you need to find first date and last date of the current year in terms of Date class instance. You can use the Calendar class for this. Construct Calendar instance using provided date class instance. Set the MONTH and DAY_OF_MONTH field to 0 and 1 respectively, then use getTime() method which will return Date class instance representing first day of year. You can use same technique to find end of year.
Date date = new Date();
System.out.println("date: "+date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println("cal:"+cal.getTime());
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("cal new: "+cal.getTime());
Update: The Joda-Time library is now in maintenance mode with its team advising migration to the java.time classes. See the correct java.time Answer by Przemek.
Time Zone
The other Answers ignore the crucial issue of time zone.
Joda-Time
Avoid doing date-time work with the notoriously troublesome java.util.Date class. Instead use either Joda-Time or java.time. Convert to j.u.Date objects as needed for interoperability.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ;
int year = 2015 ;
DateTime firstOfYear = new DateTime( year , DateTimeConstants.JANUARY , 1 , 0 , 0 , zone ) ;
DateTime firstOfNextYear = firstOfYear.plusYears( 1 ) ;
DateTime firstMomentOfLastDayOfYear = firstOfNextYear.minusDays( 1 ) ;
Convert To java.util.Date
Convert to j.u.Date as needed.
java.util.Date d = firstOfYear.toDate() ;
You can use Jodatime as shown in this thread Java Joda Time - Implement a Date range iterator
Also, you can use gregorian calendar and move one day at a time, as shown here. I need a cycle which iterates through dates interval
PS. Piece of advice: search it first.
You can use the apache commons-lang project which has a DateUtils class.
They provide an iterator which you can give the Date object.
But I highly suggest using the Calendar class as suggested by the other answers.
First and Last day of Year
import java.util.Calendar
import java.text.SimpleDateFormat
val parsedDateInt = new SimpleDateFormat("yyyy-MM-dd")
val cal2 = Calendar.getInstance()
cal2.add(Calendar.MONTH, -(cal2.get(Calendar.MONTH)))
cal2.set(Calendar.DATE, 1)
val firstDayOfYear = parsedDateInt.format(cal2.getTime)
cal2.add(Calendar.MONTH, (11-(cal2.get(Calendar.MONTH))))
cal2.set(Calendar.DATE, cal2.getActualMaximum(Calendar.DAY_OF_MONTH))
val lastDayOfYear = parsedDateInt.format(cal2.getTime)
val instance = Calendar.getInstance()
instance.add(Calendar.YEAR,-1)
val prevYear = SimpleDateFormat("yyyy").format(DateTime(instance.timeInMillis).toDate())
val firstDayPreviousYear = DateTime(prevYear.toInt(), 1, 1, 0, 0, 0, 0)
val lastDayPreviousYear = DateTime(prevYear.toInt(), 12, 31, 0, 0, 0, 0)
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(start);
while (gcal.getTime().before(end)) {
gcal.add(Calendar.DAY_OF_YEAR, 1);
//Do Something ...
}
The GregorianCalendar creation here is pointless. In fact, going through Calendar.java source code shows that Calendar.getInstance() already gives a GregorianCalendar instance.
Regards,
Nicolas
Calendar cal = Calendar.getInstance();//getting the instance of the Calendar using the factory method
we have a get() method to get the specified field of the calendar i.e year
int year=cal.get(Calendar.YEAR);//for example we get 2013 here
cal.set(year, 0, 1); setting the date using the set method that all parameters like year ,month and day
Here we have given the month as 0 i.e Jan as the month start 0 - 11 and day as 1 as the days starts from 1 to30.
Date firstdate=cal.getTime();//here we will get the first day of the year
cal.set(year,11,31);//same way as the above we set the end date of the year
Date lastdate=cal.getTime();//here we will get the last day of the year
System.out.print("the firstdate and lastdate here\n");
java.time.YearMonth
How to Get First Date and Last Date For Specific Year and Month.
Here is code using YearMonth Class.
YearMonth is a final class in java.time package, introduced in Java 8.
public static void main(String[] args) {
int year = 2021; // you can pass any value of year Like 2020,2021...
int month = 6; // you can pass any value of month Like 1,2,3...
YearMonth yearMonth = YearMonth.of( year, month );
LocalDate firstOfMonth = yearMonth.atDay( 1 );
LocalDate lastOfMonth = yearMonth.atEndOfMonth();
System.out.println(firstOfMonth);
System.out.println(lastOfMonth);
}
See this code run live at IdeOne.com.
2021-06-01
2021-06-30
I am generating all dates between two dates.
public List<Date> generateRangeDates(Date firstDate, Date lastDate) {
List<Date> allDates = new ArrayList<Date>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(firstDate);
while (calendar.getTime().before(lastDate)) {
Date resultado = calendar.getTime();
allDates .add(resultado);
calendar.add(Calendar.DATE, 1);
}
Date lastDate1 = allDates .get(dates.size()-1);
Calendar cal = new GregorianCalendar();
cal.setTime(lastDate1);
cal.add(Calendar.DATE, 1);
allDates .add(cal.getTime());
for(Date date1 : dates) {
System.out.println("All Dates : "+ date1);
}
return dates;
}
Above method generating All Dates starting from the first Date till last date. I know it has a major shortcomings. like i could have used joda-time instead of java.util.Calendar. there is also a ambiguity about daylight saving. also it didn't mention TIMEZONE. Also using GregorianCalendar, which totally ignores the current Locale.
- for the time being - I DO NOT WANT TO USE JODA API.
Help needed to update the above function which works in all TIMEZONES. I have googled a lot on this but also got confused a lot.
also a question ( might sound a bit stupid)-
Why do people insist using JODA API? doesn't it have any ambiguity?
Note - these lines generating the last date and being added in allDates list.
Date lastDate1 = allDates .get(dates.size()-1);
Calendar cal = new GregorianCalendar();
cal.setTime(lastDate1);
cal.add(Calendar.DATE, 1);
allDates .add(cal.getTime());
Is there any reason not to use long for times? If you need to use Dates you can do this.
Date is time zone independent.
public List<Date> generateRangeDates(Date firstDate, Date lastDate) {
List<Date> dates = new ArrayList<Date>();
for(long t = firstDate.getTime(); t <= lastDate.getTime(); t += 24 * 60 * 60 * 1000)
dates.add(new Date(t));
return dates;
}
You can't create a list which is complete TimeZone independent as there is no such data structure in Java.
The reason other may have suggested using JODA is it have proper Date (without time) objects as it is properly timezone independent.
I need to compare two Dates (e.g. date1 and date2) and come up with a boolean sameDay which is true of the two Dates share the same day, and false if they are not.
How can I do this? There seems to be a whirlwind of confusion here... and I would like to avoid pulling in other dependencies beyond the JDK if at all possible.
to clarify: if date1 and date2 share the same year, month, and day, then sameDay is true, otherwise it is false. I realize this requires knowledge of a timezone... it would be nice to pass in a timezone but I can live with either GMT or local time as long as I know what the behavior is.
again, to clarify:
date1 = 2008 Jun 03 12:56:03
date2 = 2008 Jun 03 12:59:44
=> sameDate = true
date1 = 2009 Jun 03 12:56:03
date2 = 2008 Jun 03 12:59:44
=> sameDate = false
date1 = 2008 Aug 03 12:00:00
date2 = 2008 Jun 03 12:00:00
=> sameDate = false
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
Note that "same day" is not as simple a concept as it sounds when different time zones can be involved. The code above will for both dates compute the day relative to the time zone used by the computer it is running on. If this is not what you need, you have to pass the relevant time zone(s) to the Calendar.getInstance() calls, after you have decided what exactly you mean with "the same day".
And yes, Joda Time's LocalDate would make the whole thing much cleaner and easier (though the same difficulties involving time zones would be present).
How about:
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));
You can also set the timezone to the SimpleDateFormat, if needed.
I use the "apache commons lang" package to do this (namely org.apache.commons.lang.time.DateUtils)
boolean samedate = DateUtils.isSameDay(date1, date2); //Takes either Calendar or Date objects
You can avoid external dependencies and the performance hit of using Calendar by calculating the Julian Day Number for each of the dates and then comparing these:
public static boolean isSameDay(Date date1, Date date2) {
// Strip out the time part of each date.
long julianDayNumber1 = date1.getTime() / MILLIS_PER_DAY;
long julianDayNumber2 = date2.getTime() / MILLIS_PER_DAY;
// If they now are equal then it is the same day.
return julianDayNumber1 == julianDayNumber2;
}
Joda-Time
As for adding a dependency, I'm afraid the java.util.Date & .Calendar really are so bad that the first thing I do to any new project is add the Joda-Time library. In Java 8 you can use the new java.time package, inspired by Joda-Time.
The core of Joda-Time is the DateTime class. Unlike java.util.Date, it understands its assigned time zone (DateTimeZone). When converting from j.u.Date, assign a zone.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeQuébec = new DateTime( date , zone );
LocalDate
One way to verify if two date-times land on the same date is to convert to LocalDate objects.
That conversion depends on the assigned time zone. To compare LocalDate objects, they must have been converted with the same zone.
Here is a little utility method.
static public Boolean sameDate ( DateTime dt1 , DateTime dt2 )
{
LocalDate ld1 = new LocalDate( dt1 );
// LocalDate determination depends on the time zone.
// So be sure the date-time values are adjusted to the same time zone.
LocalDate ld2 = new LocalDate( dt2.withZone( dt1.getZone() ) );
Boolean match = ld1.equals( ld2 );
return match;
}
Better would be another argument, specifying the time zone rather than assuming the first DateTime object’s time zone should be used.
static public Boolean sameDate ( DateTimeZone zone , DateTime dt1 , DateTime dt2 )
{
LocalDate ld1 = new LocalDate( dt1.withZone( zone ) );
// LocalDate determination depends on the time zone.
// So be sure the date-time values are adjusted to the same time zone.
LocalDate ld2 = new LocalDate( dt2.withZone( zone ) );
return ld1.equals( ld2 );
}
String Representation
Another approach is to create a string representation of the date portion of each date-time, then compare strings.
Again, the assigned time zone is crucial.
DateTimeFormatter formatter = ISODateTimeFormat.date(); // Static method.
String s1 = formatter.print( dateTime1 );
String s2 = formatter.print( dateTime2.withZone( dt1.getZone() ) );
Boolean match = s1.equals( s2 );
return match;
Span of Time
The generalized solution is to define a span of time, then ask if the span contains your target. This example code is in Joda-Time 2.4. Note that the "midnight"-related classes are deprecated. Instead use the withTimeAtStartOfDay method. Joda-Time offers three classes to represent a span of time in various ways: Interval, Period, and Duration.
Using the "Half-Open" approach where the beginning of the span is inclusive and the ending exclusive.
The time zone of the target can be different than the time zone of the interval.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime target = new DateTime( 2012, 3, 4, 5, 6, 7, timeZone );
DateTime start = DateTime.now( timeZone ).withTimeAtStartOfDay();
DateTime stop = start.plusDays( 1 ).withTimeAtStartOfDay();
Interval interval = new Interval( start, stop );
boolean containsTarget = interval.contains( target );
java.time
Java 8 and later comes with the java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See Tutorial.
The makers of Joda-Time have instructed us all to move to java.time as soon as is convenient. In the meantime Joda-Time continues as an actively maintained project. But expect future work to occur only in java.time and ThreeTen-Extra rather than Joda-Time.
To summarize java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime object. To move off the timeline, to get the vague indefinite idea of a date-time, use the "local" classes: LocalDateTime, LocalDate, LocalTime.
The logic discussed in the Joda-Time section of this Answer applies to java.time.
The old java.util.Date class has a new toInstant method for conversion to java.time.
Instant instant = yourJavaUtilDate.toInstant(); // Convert into java.time type.
Determining a date requires a time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
We apply that time zone object to the Instant to obtain a ZonedDateTime. From that we extract a date-only value (a LocalDate) as our goal is to compare dates (not hours, minutes, etc.).
ZonedDateTime zdt1 = ZonedDateTime.ofInstant( instant , zoneId );
LocalDate localDate1 = LocalDate.from( zdt1 );
Do the same to the second java.util.Date object we need for comparison. I’ll just use the current moment instead.
ZonedDateTime zdt2 = ZonedDateTime.now( zoneId );
LocalDate localDate2 = LocalDate.from( zdt2 );
Use the special isEqual method to test for the same date value.
Boolean sameDate = localDate1.isEqual( localDate2 );
Convert dates to Java 8 java.time.LocalDate
as seen here.
LocalDate localDate1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate localDate2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// compare dates
assertTrue("Not on the same day", localDate1.equals(localDate2));
Java 8
If you are using Java 8 in your project and comparing java.sql.Timestamp, you could use the LocalDate class:
sameDate = date1.toLocalDateTime().toLocalDate().equals(date2.toLocalDateTime().toLocalDate());
If you are using java.util.Date, have a look at Istvan answer which is less ambiguous.
private boolean isSameDay(Date date1, Date date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
return (sameDay && sameMonth && sameYear);
}
FOR ANDROID USERS:
You can use DateUtils.isToday(dateMilliseconds) to check whether the given date is current day or not.
API reference: https://developer.android.com/reference/android/text/format/DateUtils.html#isToday(long)
For Kotlin devs this is the version with comparing formatted strings approach:
val sdf = SimpleDateFormat("yyMMdd")
if (sdf.format(date1) == sdf.format(date2)) {
// same day
}
It's not the best way, but it's short and working.
in addition to Binil Thomas solution
public static boolean isOnSameDay(Timestamp... dates) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
String date1 = fmt.format(dates[0]);
for (Timestamp date : dates) {
if (!fmt.format(date).equals(date1)) {
return false;
}
}
return true;
}
usage
isOnSameDay(date1,date2,date3 ...);
//or
isOnSameDay(mydates);
With JAVA 8 we can convert Date object to LocalDate object, hence we can do this:
public static boolean isDatesAreDifferentDays(Date date1,Date date2)
{
LocalDate d1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate d2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
if(d1.getDayOfMonth() != d2.getDayOfMonth())
{
return false;
}
else if(d1.getMonth() != d2.getMonth())
{
return false;
}
else if(d1.getYear() != d2.getYear())
{
return false;
}
else
{
return true;
}
}
FASTER SOLUTION
Like #AyeJay solution but correct for all timezones, that add a offset in timestamp.
public static boolean isSameDay(Date dateA, Date dateB) {
int offset = TimeZone.getDefault().getRawOffset();
try {
long julianDayNumber1 = (dateA.getTime() + offset) / MILLIS_PER_DAY;
long julianDayNumber2 = (dateB.getTime() + offset) / MILLIS_PER_DAY;
return julianDayNumber1 == julianDayNumber2;
} catch (Exception e) {
return false;
}
}
you can apply the same logic as the SimpleDateFormat solution without relying on SimpleDateFormat
date1.getFullYear()*10000 + date1.getMonth()*100 + date1.getDate() ==
date2.getFullYear()*10000 + date2.getMonth()*100 + date2.getDate()