I have a Kotlin function to get the total number of weeks in a month
Code
fun getTotalWeeksInMonth(instant: Instant): Int {
val calendar = Calendar.getInstance()
calendar.time = Date.from(instant)
return calendar.getActualMaximum(Calendar.WEEK_OF_MONTH)
}
However this is using a mix of the old Java date/time APIs (Date and Calendar) and the new APIs (Instant)
How would I achieve the same result, using just the new APIs?
You can try something like this pair of lines:
YearMonth currentYearMonth =
YearMonth.now(
ZoneId.systemDefault()
)
;
int weeks =
currentYearMonth
.atEndOfMonth()
.get(
WeekFields.ISO.weekOfMonth()
)
;
You can evaluate the "week of month" of last day of this month, in java:
static int getTotalWeeksInMonth(Instant instant) {
LocalDate localDate = LocalDate.ofInstant(instant, ZoneId.systemDefault());
LocalDate lastDayOfMonth = localDate.withDayOfMonth(localDate.lengthOfMonth());
int lastWeekOfMonth = lastDayOfMonth.get(WeekFields.ISO.weekOfMonth());
return lastWeekOfMonth;
}
See if this fits you, be careful about what Zone you are actually passing, and about WeekFields.ISO, in some regions it may work fine, but in others it may not:
Instant now = Instant.now();
ZonedDateTime zonedNow = now.atZone(ZoneId.systemDefault());
ZonedDateTime monthEnd = zonedNow.with(TemporalAdjusters.lastDayOfMonth());
System.out.println(monthEnd.get(WeekFields.ISO.weekOfMonth()));
Having an Instant I would convert it to date first:
val date = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
Then go with either
YearMonth.from(date).atEndOfMonth().get(ChronoField.ALIGNED_WEEK_OF_MONTH)
or
YearMonth.from(date).atEndOfMonth().get(WeekFields.ISO.weekOfMonth())
Complete example:
fun getTotalWeeksInMonth(instant: Instant): Int {
val date = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
return YearMonth.from(date).atEndOfMonth().get(ChronoField.ALIGNED_WEEK_OF_MONTH)
}
Related
i need to find weekdays for a given date.
The given date is = 2080-03-20
Now i need to find a weekday after 5 days from the given date.
It should return:
2080-03-25
I tried this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util;
Date date=new Date();
Calendar calendar = Calendar.getInstance();
date = calendar.getTime()
SimpleDateFormat s
s= new SimpleDateFormat("yyyy-MM-dd")
Date today = new Date();
SimpleDateFormat formatedDate = new SimpleDateFormat ("yyyy-MM-dd")
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 21916);
String after60years = (String)(formattedDate.format(c.getTime()))
int days = 5;
for (int i=0;i<days;)
{
calendar.add(Calendar.DAY_OF_MONTH, 1)
if(calendar.get(Calendar.DAY_OF_WEEK)<-5)
{
i++;
}
}
date = calendar.getTime();
s=new SimpleDateFormat("yyyy=MM-dd");
System.println(s.format(date+21916));
It returns:
2080-03-19
2080-03-26
Is this solution is correct ?
Will it return always weekday after 5 days from the given date.
Any help, thank you
tl;dr
LocalDate
.now(
ZoneId.of( "America/Montreal" )
)
.plusDays( 5 )
.with(
org.threeten.extra.Temporals.nextWorkingDayOrSame()
)
java.time
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
TemporalAdjuster
Apparently you want to move a certain number of days into the future, but not counting weekend days of Saturday and Sunday.
In java.time, we move to another date by way of a TemporalAdjuster.
ThreeTen-Extra
Your could write your own adjuster for skipping the weekend.
nextWorkingDay
But no need, we have an implementation available to us in the ThreeTen-Extra library: org.threeten.extra.Temporals.nextWorkingDay
TemporalAdjuster ta = org.threeten.extra.Temporals.nextWorkingDay() ;
Use that adjuster in a loop for your count of days.
LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
LocalDate date = today ;
int daysAhead = 5 ;
List< LocalDate > dates = new ArrayList<>( daysAhead ) ;
for( int i = 1 ; i <= daysAhead ; i ++ )
{
date = date.with( ta ) ;
dates.add( date ) ;
}
nextWorkingDayOrSame
If by your Question you meant skip five days later, then determine if that date is a weekday, if not move to the next weekday, then we use the temporal adjuster nextWorkingDayOrSame.
LocalDate today = LocalDate.now( ZoneId.of( "Asia/Tokyo" ) ) ;
int daysAhead = 5 ;
LocalDate later = today.plusDays( daysAhead ) ;
LocalDate date = later.with( org.threeten.extra.Temporals.nextWorkingDayOrSame() ) ;
Using java.time:
public LocalDate weekdayAfter5Days(LocalDate date) {
var target = date.plusDays(5);
var weekday = target.getDayOfWeek();
if (weekday == DayOfWeek.SATURDAY || weekday == DayOfWeek.SUNDAY) {
var nextMonday = TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY);
target = target.with(nextMonday);
}
return target;
}
If date is given as a string with format yyyy-MM-dd just create a LocalDate:
var date = LocalDate.parse(text);
or, for a different format (e.g. dd/MM/yyyy):
var date = LocalDate.parse(text, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
Java8 provides java.time library with rich features. You may try the following sample code.
public class TimeTest {
private static TemporalAdjuster TEMPORAL_ADJUSTER = TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY);
private static List<DayOfWeek> OFF_DAYS = Arrays.asList(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY);
public static void main(String[] args) {
LocalDate localDate = LocalDate.parse("2080-03-20");
long daysToPlus = 5l;
for (int day = 1; day <= daysToPlus; day++) {
localDate = localDate.plusDays(1);
if (OFF_DAYS.contains(localDate.getDayOfWeek())) {
localDate = localDate.with(TEMPORAL_ADJUSTER);
}
}
System.out.println(localDate);
System.out.println(localDate.getDayOfWeek());
}
}
I have two java.time.Instant objects
Instant dt1;
Instant dt2;
I want to get time (only hours and minutes without date) from dt2 and set it to dt1. What is the best way to to this? Using
dt2.get(ChronoField.HOUR_OF_DAY)
throws java.time.temporal.UnsupportedTemporalTypeException
You have to interpret the Instant at some time zone to get ZonedDateTime. As an Instant measures the ellapsed seconds and nano seconds from epoch 1970-01-01T00:00:00Z you should use UTC to get the same time as the Instant would print. (Z ≙ Zulu Time ≙ UTC)
Getting the time
Instant instant;
// get overall time
LocalTime time = instant.atZone(ZoneOffset.UTC).toLocalTime();
// get hour
int hour = instant.atZone(ZoneOffset.UTC).getHour();
// get minute
int minute = instant.atZone(ZoneOffset.UTC).getMinute();
// get second
int second = instant.atZone(ZoneOffset.UTC).getSecond();
// get nano
int nano = instant.atZone(ZoneOffset.UTC).getNano();
There are also methods to get days, month and year (getX).
Setting the time
Instants are immutable so you can only "set" the time by creating a copy of your instant with the given time change.
instant = instant.atZone(ZoneOffset.UTC)
.withHour(hour)
.withMinute(minute)
.withSecond(second)
.withNano(nano)
.toInstant();
There are also methods to alter days, month and year (withX) as well as methods to add (plusX) or subtract (minusX) time or date values.
To set the time to a value given as a string use: .with(LocalTime.parse("12:45:30"))
Instant does not have any hour / minute. Please read the documentation of Instant class : https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html
If you use System Timezone to convert the Instant , you can use something like this :
LocalDateTime ldt1 = LocalDateTime.ofInstant(dt1, ZoneId.systemDefault());
LocalDateTime ldt2 = LocalDateTime.ofInstant(dt2, ZoneId.systemDefault());
ldt1 = ldt1
.withHour(ldt2.getHour())
.withMinute(ldt2.getMinute())
.withSecond(ldt2.getSecond());
dt1 = ldt1.atZone(ZoneId.systemDefault()).toInstant();
Convert first the Instant to LocalDateTime, and use UTC as its timezone, then you can get its hours.
import java.time.*
LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC).getHour()
While the upper answer is a good, I used it but in Kotlin. Thankyou #frido
while (startDate.isBefore(endDate)) {
val year: Int = startDate.atZone(ZoneOffset.UTC).year
val month: Int = startDate.atZone(ZoneOffset.UTC).monthValue
val day: Int = startDate.atZone(ZoneOffset.UTC).dayOfMonth
System.out.printf("%d.%d.%d\n", day, month, year)
startDate = startDate.atZone(ZoneOffset.UTC).withDayOfMonth(
day + 1
).toInstant()
}
I want to compare two different time stamp using System.currentTimeMillis().
Basically I want to check whether the time stamps are within 3 hours range on a particular day.
How to do this?
Considering you have time1 and time2, where time1 <= time2 you can do this:
if (time1 >= time2-(60*60*3*1000)) {
// interval is up to 3 hours
} else {
// interval is more than 3 hours
}
Use Instant to get the time in the epoch and convert it to LocalDateTime to get the information about the day and check, if the first time plus 3 hours is smaller than the second time:
long millis1 = System.currentTimeMillis();
...
long millis2 = System.currentTimeMillis();
Instant instant1 = Instant.EPOCH.plusMillis(millis1);
Instant instant2 = Instant.EPOCH.plusMillis(millis2);
LocalDateTime t1 = LocalDateTime.ofInstant(instant1, ZoneId.systemDefault());
LocalDateTime t2 = LocalDateTime.ofInstant(instant2, ZoneId.systemDefault());
System.out.println("same day: " + (t1.getDayOfYear() == t2.getDayOfYear()));
System.out.println("t1+3h >= t2: " + (t1.plusHours(3).compareTo(t2) >= 0));
Here is a sample program that might help you out. The crux here is the method "findIfDatesWithinThreeHours" which helps whether to find if two instances are three hours apart.
package com.inrvu.adapter;
import java.util.Calendar;
import java.util.Date;
public class Tester {
public static void main(String[] args) {
Date[] dates = getTwoDatesThreeHoursApart();
System.out.println(String.format("%b", findIfDatesWithinThreeHours(dates[0],dates[1])));
dates = getTwoDatesWithinThreeHours();
System.out.println(String.format("%b", findIfDatesWithinThreeHours(dates[0],dates[1])));
}
public static Date[] getTwoDatesThreeHoursApart()
{
Calendar calendar = Calendar.getInstance();
Date date1 = calendar.getTime();
calendar.add(Calendar.HOUR,4);
Date date2 = calendar.getTime();
return new Date[]{date1,date2};
}
public static Date[] getTwoDatesWithinThreeHours()
{
Calendar calendar = Calendar.getInstance();
Date date1 = calendar.getTime();
calendar.add(Calendar.HOUR,3);
Date date2 = calendar.getTime();
return new Date[]{date1,date2};
}
public static boolean findIfDatesWithinThreeHours(Date date1, Date date2) {
// here the time of a single hour is defined as 60*60*1000
System.out.println(date1);
System.out.println(date2);
return Math.abs(date1.getTime()-date2.getTime()) <= 3*60*60*1000;
}
}
Your Question is vague. This might get you pointed in the right direction.
If by "timestamp" you meant a count of milliseconds since the epoch of 1970 UTC, construct an Instant. This class represents a moment on the timeline in UTC with a resolution of nanoseconds (finer than milliseconds).
Instant instant = Instant.ofEpochMilli( millis );
Get current moment.
Instant now = Instant.now();
Calculate three hours.
Instant in3Hours = now.plus( 3 , ChronoUnit.HOURS );
See if your moment lies between now and three hours later.
Boolean contained = ( ( ! instant.isBefore( now ) ) && instant.isBefore( in3Hours ) );
If you meant you want to compare a pair of moments to see if the elapsed time is less than 3 hours, use a Duration. This class represents a span of time in terms of seconds and nanoseconds.
Instant earlierInstant = … ;
Instant laterInstant = … ;
Duration duration = Duration.between( earlierInstant , laterInstant );
if ( duration.isNegative() ) {
… handle error of unexpected data inputs where the second instant is *before* the first instant.
}
… else …
Boolean elapsedUnderThreeHours = ( duration.compareTo( Duration.ofHours( 3 ) ) == -1 );
I am trying to get time zone from an existing date to use it for some other date conversion. Can someone reply with updating the todos in the below code. Appreciate any help.
Or just to make it simple is there some java api to which i give +0530 and it returns IST :)
Here is my code :
import java.text.SimpleDateFormat
import java.util.*;
import java.text.DateFormat;
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = isoFormat.parse("2016-04-21T00:00:00+0530");
//todo print time zone
//todo here should print IST since date is having +0530
This is not possible. A Date does not have time zone information attached. It is just a point in time, internally represented as milliseconds since 1.1.1970 midnight UTC (excluding leap seconds).
A java.util.Date does not have a time zone. It is a pure time in UTC. The parser converted the string to the internal value.
A java.time.ZonedDateTime (Java 8+) does have a time zone.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ");
ZonedDateTime dt = ZonedDateTime.parse("2016-04-21T00:00:00+0530", formatter);
ZoneId zone = dt.getZone();
If running Java 6 or 7, use the backport of the Java SE 8 date-time classes.
For Java 5+ use the Joda-Time library.
Just to answer myself so that it might help some one else :
I was having date as string as input lets say :
String startDate = "2016-04-21T00:00:00+0530"
//i can calculate the timezone offset using
String offSet = startDate.substring(startDate.length() - 5) //gives +0530
Method used to calculate timezone. Here we give offset calculated above and the below method returns the TimeZone object:
public static TimeZone fetchTimeZone(String offset) {
if (offset.length() != 5) {
return null
}
TimeZone tz
Integer offsetHours = Integer.parseInt(offset.substring(0, 3))
Integer offsetMinutes = Integer.parseInt(offset.substring(3))
String[] ids = TimeZone.getAvailableIDs()
for (int i = 0; i < ids.length; i++) {
tz = TimeZone.getTimeZone(ids[i])
long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset())
long minutes = Math.abs(TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset()) % 60)
if (hours != offsetHours || minutes != offsetMinutes) {
tz = null
} else {
break
}
}
return tz
}
Finally i use the Timezone from above method to format any date to that timezone :
SimpleDateFormat timeZonedFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
TimeZone timeZone = fetchTimeZone(offSet) //from above method and offset from first code
timeZonedFormatter.setTimeZone(timeZone);
//this timeZonedFormatter can be used to format any date into the respective timeZone
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()