Java - Check whether two Dates are Equal - java

I am trying to compare dates in two different formats:
Tue Jul 01 00:12:14 EST 2014
which is created using the function:
private Date getDate (int day, int month, int year){
Calendar calendar = Calendar.getInstance();
calendar.setLenient(false);
calendar.set(year, month-1, day);
Date date = calendar.getTime();
return date;
}
and
2014-07-01
After comparing these two dates, I would like the output to show that they are equal. However I BELIEVE, because of the timestamp in the 1st Date, they are not being determined as equal.
Is my assumption correct?
If so, is there a way that I could convert the first date into the second? The second Date is being retrieved from an SQL database where the variable is DATE.
Thank you for your help.

It sounds like you are comparing a java.util.Date (an instant in time) with a java.sql.Date (an instant in time whose time of day is midnight).
Arithmetic rounding must deal with the local timezones, making it more complex than you might first think.
The simplest way to compare the two would be to use a data formatter and compare the output:
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
if (f.format(date1).equals(f.format(date2))) {
// the two dates are on the same "day"
}

java.sql.Date Has Zero Time
The documentation explains that a java.sql.Date has its time portion set to zero (UTC), meaning midnight.
So when comparing to a java.util.Date with a non-zero time-of-day, the two will not be equal.
LocalDate
So much easier using Joda-Time of the new java.time package in Java 8. Both offer a LocalDate class that ignores time-of-day.
LocalDate x = new LocalDate( 2014, 5, 6 );
LocalDate y = new LocalDate( 2014, 5, 6 );
boolean same = x.equals( y );
To convert your java.sql.Date to a Joda-Time LocalDate, pass it to the constructor of New LocalDate. You may need to also pass DateTimeZone.UTC to be sure it is not interpreted by your JVM's default time zone.

Is my assumption correct?
Yes, your assumption is correct. Two Date instances are correct if both their getTime() results are the same
from Date.java
public boolean equals(Object obj) {
return obj instanceof Date && getTime() == ((Date) obj).getTime();
}
Converting just assumes you need to set the hours,minutes and seconds to 0:
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);

Assuming that both dates are in the same timezone and also assuming that the date equality criteria here is the day of the year, I believe you can just compare the date as strings.
To do that, you can use SimpleDateFormat to ensure both are in the same format.

I would suggest you convert both of them to one particular format and compare them using a Comparator.

If you need to check whether two dates are equal, the best way is to use compareTo method.
if(yesterday.compareTo(today) == 0) {
System.out.println("Given dates are same");
} else {
System.out.println("Given dates are different ");
}
Read more: https://www.java67.com/2016/09/how-to-compare-two-dates-in-java.html#ixzz6uH5r1xE2

Related

Subtracting one day off Calendar doesn't work

I am trying to build a simple program with java.util.Calendar. When trying to get the weekday before, my output always stays the same. Code and what I tried below:
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
c.set(Calendar.YEAR, year);
int date = c.get(Calendar.DAY_OF_WEEK);
return new SimpleDateFormat("EEEE").format(date).toUpperCase();
This was my code at the start. I have tried subtracting day by one:
day = day-1;
I have tried adding minus one to both the Day of Month and Day of week field:
c.add(Calendar.DAY_OF_WEEK, -1);
c.add(Calendar.DAY_OF_MONTH, -1);
I think that it has something to do with my SimpleDateFormat, but I am not sure.
I am trying to build a simple program with java.util.Calendar.
That is impossible. Specifically, the 'simple program' part. Nothing that uses Calendar is simple.
The calendar API is horrible; it makes no sense (the first month of the year is... 0, to change values, you have to use int constants, which isn't idiomatic java), and is confused about what it is trying to represent (it's not a calendar, it's a date/time value, or, is it? Is it solarflares time, appointment time, or alarmclock time? It's confused and doesn't know). That's why there is a new API: java.time. Java does not remove stuff even if it is obsolete, because that would break old code. So, the fact that Calendar is still around doesn't mean much.
Use java.time.
I think that it has something to do with my SimpleDateFormat, but I am not sure.
It doesn't. But let's forget about this silly API and use java time instead!
// note that in calendar, january is 0, and that is insane.
// in localdate, it is 1, which is sane.
// thus, assuming you have `month = month - 1;` someplace in your code...
// remove that.
LocalDate date = LocalDate.of(year, month, day);
DayOfWeek day = date.getDayOfWeek();
System.out.println(day);
Wanna go back a day? Okay.
DayOfWeek day = date.minusDays(1).getDayOfWeek();
System.out.println(day);
The reason this fails is that you aren't invoking the method you think you are. There is no SimpleDateFormat#format(int). But SimpleDateFormat extends Format, which declares Format#format(Object). Your int is boxed to Integer and then the relevant code in Format#format(Object) is
if (obj instanceof Date)
return format( (Date)obj, toAppendTo, fieldPosition );
else if (obj instanceof Number)
return format( new Date(((Number)obj).longValue()),
toAppendTo, fieldPosition );
else
throw new IllegalArgumentException("Cannot format given Object as a Date");
At this point, since the value you passed is boxed to Integer which extends Number, the second branch of the if-else is taken and your day-of-week value is converted to a date via the constructor. The number is interpreted as a millisecond value and when you subtracted 1 you changed the time by 1 millisecond, not 1 day.
All that said, you should NOT be using Calendar, use the new date/time API in the java.time package.

Check current date java [duplicate]

This question already has answers here:
Compare two dates in Java
(13 answers)
Closed 4 years ago.
From java class Date docs:
before(Date when) Tests if this date is before the specified date.
When I use this method to test whether selected date is equal to today, I get wrong output message.
public class JavaApplication28 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws NoSuchAlgorithmException, ParseException {
Date date1;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String statusDT ="2018-04-08";
date1 = formatter.parse(statusDT);
if (date1.equals(new Date())) {
System.out.println("today");
} else if (date1.before(new Date())) {
System.out.println("wrong");
}
}
}
This is date1, which is today date
Sun Apr 08 00:00:00 MYT 2018
The equal method look not functiong as well
equals(Object obj) Compares two dates for equality.
The given date date1 represent today but with midnight time : Sun Apr 08 00:00:00 MYT 2018
the date used for comparison new Date() represents also today but the actual time (about 15h10) : Sun Apr 08 15:10:00 MYT 2018
So date1 if before actual Date() and it goes in the good if section
As the Java8 introduce a new Date API, it's easier to use in most case :
LocalDateTime which holds Date (day/month/year) and Time (sec/min/hour)
LocalDate which holds the Date part and can be given from a LocalDateTime.toLocalDate()
LocalTime which holds the Time part and can be given from a LocalDateTime.toLocalTime()
So if you don't matter of the time, and just want to check the day/month/year you can use only the LocalDate part from the LocalDateTime :
if (date1.toLocalDate().equals(LocalDate.now())) {
System.out.println("today"); //< ---
} else if (date1.toLocalDate().isBefore(LocalDate.now())) {
System.out.println("before now");
} else if (date1.toLocalDate().isAfter(LocalDate.now())) {
System.out.println("after now");
}
Try this :
long l1 = date1.getTime();
long l2 = (new Date()).getTime();
Output
1523142000000
1523192849177
The doc said :
Compares two dates for equality. The result is true if and only if the
argument is not null and is a Date object that represents the same
point in time, to the millisecond, as this object. Thus, two Date
objects are equal if and only if the getTime method returns the same
long value for both.
Your get wrong because you thing that equal compare only the date part, but NO, it also compare the time part
Another Solution
Because you are using Java 8 why not using java.time instead like this :
String statusDT = "2018-04-08";
LocalDate date = LocalDate.parse(statusDT, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
if (date.isEqual(LocalDate.now())) {
System.out.println("today");
} else if (date.isBefore(LocalDate.now())) {
System.out.println("before");
} else {
System.out.println("after");
}
Class java.util.Date contains both a date and a time-of-day - as can be seen in the output of your program. The Date you obtain by parsing the String has no time-of-day, only a date. In other words, its time-of-day is 00:00 (i.e. midnight). Hence the two Dates are not equeal.
And by the way, the link you provided for the javadoc of the Date class is the Java 8 documentation. If this means you are using Java 8, then there is a new Date-Time API. There is a tutorial at
https://docs.oracle.com/javase/tutorial/datetime/index.html

How to check if first date is older than second?

First I get:
LocalDate today = LocalDate.now();
and second
Date date = new Date();
date.setDate(Integer.valueOf(s[0]));
date.setMonth(Integer.valueOf(s[1]));
date.setYear(Integer.valueOf(s[2]));
LocalDate topicDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
How to check whether the differences between the first date and the second is 7 days?
For example, today is 03-08-2015 and the second date is 20-07-2015 and the difference between is more than 7 days, but how to check this?
Should I convert date to millisecond?
I Believe that is still the best way at the moment.
You can view some insights on the subject here:
Calculate date/time difference in java
You could convert to milliseconds or you could individually check if the year was larger, then if they are the same check to see if the month is larger then check day. Converting to milliseconds would be very easy though.
I believe you are looking for something like this:
Date date = /*your date object you want to compare*/;
Instant now = Instant.now();
Instant sevenDaysFromYourDate = Instant.ofEpochMilli(date.getTime()).plus(Duration.ofDays(7));
if (now.isAfter(sevenDaysFromYourDate)) {
//today is more than seven days past date
}
LocalDate today = LocalDate.now();
if (topicDate.isAfter(today.plusDays(7))) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
Since you are using Java 8 LocalDate, you can use the plusDays or minusDays methods of the LocalDate class.
Furthermore, you shouldn't be using an (old, not recommended for use) java.util.Date object to create your second date. It's better to use LocalDate.of which builds a date from the year, month and day.
Example code:
LocalDate today = LocalDate.now();
LocalDate topicDate = LocalDate.of(
Integer.valueOf(s[2]),
Integer.valueOf(s[1]),
Integer.valueOf(s[0]));
System.out.println(today);
System.out.println(topicDate);
if ( today.minusDays(7).equals(topicDate)) {
System.out.println( "Exactly a week difference between today and topicDate");
} else if ( today.minusDays(7).compareTo(topicDate) > 0 ) {
System.out.println("TopicDate is more than a week before today");
} else {
System.out.println("TopicDate is less than a week before today");
}
Note that you can use the compareTo for exact equality as well - I just wanted to demonstrate that for equality, equals also works.
And of course, there are the isAfter and isBefore methods that also do the comparison in an elegant way.

Comparing time stored in a String

I have a time in string format like "02:00" in 24 hours and I want to check it between two other time,such that "07:00"and "15:oo" .How can I check for this, as the time is in string format ?
I use the following code:
SimpleDateFormat simpDate = new SimpleDateFormat("kk:mm");
String s2=simpDate.format(date);
JLabel1.setText(s2);
now I want to check if that String s2 is inbetween "7:00" and "15:00" then set the value to another JLabel named JLabel2 as: "First Shift"
You use a SimpleDateFormat to convert the String to a Date. Then you can compare the dates together.
Read more about SimpleDateFormat here.
First, you need to parse your strings to Date object instances. You can use the DateFormat derived classes to do so (i.e. SimpleDateFormat).
Then, you can do comparisons using the millisecond-representation of both dates (obtained via getTime()) or just compare them using either after(Date date) or before(Date date).
If you need more complex operations you should use the Calendar class.
Besides, if your project works a lot with dates I'd suggest using Joda Time
EDIT (in response to comment):
Using Calendar class it would be this way. First you need a calendar instance for your 7:00 date:
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.DATE, 12); // The day of month you are working with
cal1.set(Calendar.MONTH, 7); // The month of the year
cal1.set(Calendar.YEAR, 2012); // The year
cal1.set(Calendar.HOUR_OF_DAY, 7); // Hour in 24-hours fashion
cal1.set(Calendar.MINUTE, 0); // self-explanatory
cal1.set(Calendar.SECOND, 0);
Date shiftStart = cal1.getTime();
Then do the same for the end of the shift:
Calendar cal2 = Calendar.getInstance();
cal2.set( ... ); // Repeat almost every field from previous snippet
cal2.set(Calendar.HOUR_OF_DAY, 15); // Hour in 24-hours fashion
Date shiftEnd = cal2.getTime();
Then, you just need to check the date you want to compare is between those:
Date myDate = ... // the date you want to compare
boolean checkShift = myDate.after(shiftStart) && myDate.before(shiftEnd);
Anyway, as I already said, if you will work with dates a lot in you project I would use Joda Time, as it will ease a lot date handling.

What is the proper way to remove the time part from java.util.Date? [duplicate]

This question already has answers here:
Java Date cut off time information
(20 answers)
Closed 8 years ago.
I want to implement a thread-safe function to remove the time part from java.util.Date.
I tried this way
private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
public static Date removeTimeFromDate(Date date) {
Date returnDate = date;
if (date == null) {
return returnDate;
}
//just have the date remove the time
String targetDateStr = df.format(date);
try {
returnDate = df.parse(targetDateStr);
} catch (ParseException e) {
}
return returnDate;
}
and use synchronized or threadLocal to make it thread-safe.
But it there any better way to implement it in Java. It seems this way is a bit verbose.
I am not satisfied with it.
A Date object holds a variable wich represents the time as the number of milliseconds since epoch. So, you can't "remove" the time part. What you can do is set the time of that day to zero, which means it will be 00:00:00 000 of that day. This is done by using a GregorianCalendar:
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
gc.set(Calendar.HOUR_OF_DAY, 0);
gc.set(Calendar.MINUTE, 0);
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);
Date returnDate = gc.getTime();
A Date holds an instant in time - that means it doesn't unambiguously specify a particular date. So you need to specify a time zone as well, in order to work out what date something falls on. You then need to work out how you want to represent the result - as a Date with a value of "midnight on that date in UTC" for example?
You should also note that midnight itself doesn't occur on all days in all time zones, due to DST transitions which can occur at midnight. (Brazil is a common example of this.)
Unless you're really wedded to Date and Calendar, I'd recommend that you start using Joda Time instead, as that allows you to have a value of type LocalDate which gets rid of most of these problems.

Categories

Resources