Comparing Database Date with Java Date [duplicate] - java

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?

Related

How to make a list of dates between two dates [duplicate]

This question already has answers here:
how to get a list of dates between two dates in java
(23 answers)
Closed 2 years ago.
I'm trying to create a list of dates that are included between two dates. Here is how I tried to do it :
public void fillDates() {
long diffInMillis = Math.abs(secondDate.getTime() - firstDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);
for (int i=0; i <= diff; i++) {
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.DAY_OF_MONTH)+i);
Long date = calendar.getTime().getTime();
String str = convertDate(date);
dates.add(str);
}
}
dates is a list of strings, and convertDate() is converting a long date into a string date. But I think the problem comes from the lines above, as the same day is added to the list every time.
I know other similar questions exists, but I didn't find any that really helped me... But if you have an entirely different solution for me, don't hesitate ! I'm just trying to get a list of (string) dates between two dates that are submitted by the user through Date Pickers.
You should not be using Calendar, Date or SmipleDateFormat. They're troublesome. You are better off using classes from the java.time package.
If both firstDate and secondDate are LocalDates, then it'll become much easier:
List<String> dateStrings = firstDate.datesUntil(secondDate.plusDays(1))
.map(date -> date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
.collect(Collectors.toList());
Note that datesUntil exists since Java 9. For Java 8, this is a helper method instead:
public static Stream<LocalDate> datesUntil(LocalDate from, LocalDate toExclusive) {
long daysBetween = ChronoUnit.DAYS.between(from, toExclusive);
return Stream.iterate(from, t -> t.plusDays(1))
.limit(daysBetween);
}

How to operate with time/date values on Java? [duplicate]

This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Time comparison
(12 answers)
Closed 2 years ago.
I'm working on a Java program where the user, at some point, give us as an input two times (in format String). We can assume the times are from the same day. For example in the console:
Please introduce time 1:
16:00
Please introduce time 2:
10:00
My program will capture those two time values as a String and my idea was to parse it into an object of class Date.
How could I calculate which time goes first in the course of a day?
For the previous example, I would like to print the first time that takes place on the day.
How can I properly do the following?
if (date1 <= date2) System.out.println(date1); //Suppose date1 and date2 are Date objects
else System.out.println(date2);
String firstDateString = "16:00";
String secondDateString = "10:00";
LocalTime firstLocalTime = LocalTime.parse(firstDateString, DateTimeFormatter.ofPattern("HH:mm"));
LocalTime secondLocalTime = LocalTime.parse(secondDateString, DateTimeFormatter.ofPattern("HH:mm"));
if (firstLocalTime.isAfter(secondLocalTime)) {
System.out.println(secondLocalTime);
} else {
System.out.println(firstLocalTime);
}

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

Java Date time issue [duplicate]

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).

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