Java Date time issue [duplicate] - java

This question already has answers here:
Comparing two java.util.Dates to see if they are in the same day
(14 answers)
Closed 6 years ago.
I have a problem with Date instance. I did the following:
Date startDate = new Date(); //this is from database value
Date todayDate = new Date(); //this is created locally
Now when am trying to compare them, the only issue is that the Date instance will have time, so when I check if they are equal it probably wouldn't give the same thing I expect, but rather less or more. I tested the following:
System.out.println(rsv.startDate);
System.out.println("Today date:"+todayDate);
if(rsv.startDate.equals(todayDate)){
System.out.println("Equal!");
}else if(rsv.startDate.after(todayDate)){
System.out.println("After!!");
}else{
System.out.println("Before!!!!");
}
and although both are 5th feb but it shows output of Before instead of equal. How can I remedy this? I know about SimpleDateFormat but that would change the date to strings.
Thanks,

For Date operation you can use Joda utility. Following snippet code shows compare two date :
DateTime one = new DateTime(original-Date-1);
DateTime two = new DateTime(original-Date-2);
LocalDate oneDate = one.toLocalDate();
LocalDate twoDate = two.toLocalDate();
return oneDate.compareTo(twoDate);
You can see: http://joda-time.sourceforge.net/index.html

You can strip out the time from the current Date object:
Date date = new Date();
Calendar dCal = Calendar.getInstance();
dCal.setTime(date);
dCal.set(Calendar.HOUR_OF_DAY, 0);
dCal.set(Calendar.MINUTE, 0);
dCal.set(Calendar.SECOND, 0);
dCal.set(Calendar.MILLISECOND, 0);
date = dCal.getTime();
And then make your comparision.
Alternatively, if you need in your project more date/time processing power, you can use joda date time library: http://joda-time.sourceforge.net
MidnightDate class is suitable for this specific usecase: http://joda-time.sourceforge.net/api-release/org/joda/time/DateMidnight.html

Date contains both the date and time. Equals() will only return true if the time is also the same. To make the comparison work, you need to make sure that the time portion of both Date objects is the same (eg all set to zero).

Related

Comparing Database Date with Java Date [duplicate]

This question already has answers here:
Java SimpleDateFormat always returning January for Month
(4 answers)
SimpleDateFormatter does not recognize months
(4 answers)
Closed 3 years ago.
I am building an app using hibernate(spring-jpa more specifically).
My model class contain a java.util.Date field and I want to filter the records based on the date field ignoring the time part.
I try to achieve this with spring-jpa specification but for equal operation it always returns 0 objects
I further debug this problem and found that when hibernate return the Object with field type is java.sql.timeStamp where I compare it with java.util.Date so it never matched.
Below is sample code I used for debugging
List<EmployeeLeaves> l = empLeaveDao.findAll();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-DD");
Date date = formatter.parse("2018-04-28");
long time = date.getTime();
date = new java.sql.Timestamp(time);
for (EmployeeLeaves d : l) {
System.out.println(d.getAppliedOn().getClass().getName());
if (d.getAppliedOn().equals(date)) {
System.out.println("==============" + d.getRecordId());
}
}
return l;
Still no luck as two date Objects never match as equals method never returns true.
Can anyone suggest how to create a new Date object so It can equal with Date objects returned by database.
You can use function Date.compareTo() as in this artile enter link description here
I also tested with this small code snippet, it works as expected
Date date = new Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
System.out.println(date.compareTo(sqlDate) == 0);
Also if you use java8, why don't you change the date type in Entity class to LocalDate and you would not have this kind of problem?

DatePicker setting month wrong

Can anyone tell me why the date is being set to next month instead of this month?
Even though im setting the dateFormatted variable as "28/08/2014" its setting the date to "28/07/2014".
I can simply go -1 at the month but it will mess up the date in January.
Is there some other way i should be setting the date?
Thanks
UtilDateModel model;
JDatePanelImpl datePanel;
DatePickerImpl datePicker;
model = new UtilDateModel();
model.setDate(yearInt, monthInt, dayInt);
model.setSelected(true);
datePanel = new JDatePanelImpl(model);
datePicker = new JDatePickerImpl(datePanel);
// String dateFormatted = (String) result[1];
String dateFormatted = "28/08/2014";
System.out.println("Date Formatted : " + (String) result[1]);
int day = Integer.parseInt(dateFormatted.substring(0, 2)); // Correct
int month = Integer.parseInt(dateFormatted.substring(3, 5)); // Correct
int year = Integer.parseInt(dateFormatted.substring(6, 10)); // Correct
System.out.println(day);
System.out.println(month);
System.out.println(year);
model.setDate(year, month, day);
model.setSelected(true);
You're doing date parsing wrong, please use a SimpleDateFormat or the like
The problem that you are seeing is probably related to the fact that some fields are 0-based and some are 1-based.
UPDATE
Dates should not be stored as strings in the database, instead use the available date types.
Date parsing in general is much trickier than you might think. DST, leap years, language,... all comes into play.
The newest java iteration has a complete rewrite for date handling based on joda time (http://www.joda.org/joda-time/) but you can also use the "old" way of date parsing in java which is not bad, simply different.
You should look at the javadoc of SimpleDateFormat, it will tell you why you need lower case "yyyy" for example and upper case "MM". The formatter will give you a Date which you can probe with Calendar for the required fields.
All the while it will take into account all the niggling details about date handling.
I'm not known with the 'JDatePicker' package, but after doing some research, i've found this, please read article 3 on this page. It says month number is 0 based, so januari should be 0 ( 1st month minus 1).

Java - Check whether two Dates are Equal

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

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