I have a form passing dates to my backend in CET format:
EEE MMM dd HH:mm:ss zzz yyyy
now I want to convert this Date in another one with the format yyyy-MM-dd
I don't want a String, I want transform it in a java.util.Date (I can't use LocalDate or LocalDateTime) with the above format.
if I try something like this:
Date date = new Date(); // Wed Mar 13 00:00:00 CET 2024
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
String oldDate = dt.format(date);
System.out.println(oldDate); // 2024-03-13
Date newDate = dt.parse(oldDate); // return Wed Mar 13 00:00:00 CET 2024 again
Is there a way to switch the format of the java.util.Date?
The problem is that the form send me a java.util.Date as I explain above, now - in SQL - I have to compare this date with another one extract from DB. And from DB my date is extract as 'yyyy-MM-dd'.
I'm try with H2 and PostgreSQL but the result is the same, how can I compare this two date in different format?
The Entity is something like that:
@Entity
@Table(name="test")
public class Test implements Serializable {
private java.util.Date data;
}
and the query is a projection like this:
@Query("select new it.TestDto(...)"
+ " from Test t"
+ " where (:originDate >= t.data)")
public Test test(@Param("originDate") Date originDate)
I don't know how solve this..
tl;dr
Details
Date-time objects do not have a “format”. Text has a format. Date-time objects are not text.
Yes, you can.
You can easily convert back and forth between the terribly flawed legacy classes and their modern replacements in the java.time classes. You’ll find new conversion methods added to the old classes.
In 2024, there is no reason to still be using those bloody awful date-time classes:
Calendar,Date,Date,SimpleDateFormat,Timestamp, etc.Immediately convert from legacy class to modern class.
The
java.util.Dateclass was replaced byjava.time.Instant.You seem to want only the date portion of this value which is date with time-of-day as seen in UTC.
Determining a date requires a time zone. For any given moment, the date varies around the globe by time zone. “Tomorrow” in Tokyo Japan can be simultaneously “yesterday” in Toledo Ohio US.
Apparently you want the date as perceived in central Europe. So specify your desired time zone. I’ll arbitrarily choose one such zone for this example.
Adjust from UTC to that zone.
Extract the date portion.
Generate text in standard ISO 8601 format. For a date, that is YYYY-MM-DD.
But you should be using smart objects rather than dumb text to communicate with your database.
As for your database… Jakarta Persistence, Hibernate, JDBC 4.2+, and the JDBC drivers for both Postgres and H2 have all been modernized to support the java.time classes.