change java.util.Date format

87 Views Asked by At

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

1

There are 1 best solutions below

0
Basil Bourque On

tl;dr

myPreparedStatement
.setObject(                           // In JDBC 4.2 and later, use `setObject` to communicate a *java.time* object. 
    … ,
    myJavaUtilDate                    // Flawed legacy class, `java.util.Date`, represents a moment as seen with an offset from UTC of zero hours-minutes-seconds.   
    .toInstant()                      // Returns an `Instant` object, with `java.time.Instant` being the replacement class for `java.util.Date`.
    .atZone(                          // Adjust from an offset from UTC of zero to a particular time zone.
        ZoneId.of( "Europe/Berlin" )  // Specify a time zone in `Continent/Region` style. 2-4 letter pseudo-zones like "CET" are *not* real time zones. 
    )                                 // Returns a `ZonedDateTime` object.
    .toLocalDate()                    // Extract the date portion only from a `ZonedDateTime` object representing a date, time-of-day, and time zone. Returns a `LocalDate` object.
);

Details

convert this Data in another one with the format yyyy-MM-dd

Date-time objects do not have a “format”. Text has a format. Date-time objects are not text.

I can't use LocalDate

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.

the form send me a java.util.Date

Immediately convert from legacy class to modern class.

The java.util.Date class was replaced by java.time.Instant.

Instant = myJavaUtilDate.toInstant() ;

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.

ZoneId z = ZoneId.of( "Europe/Berlin" ) ;

Adjust from UTC to that zone.

ZonedDateTime zdt = instant.atZone( z ) ;

Extract the date portion.

LocalDate ld = zdt.toLocalDate() ;

Generate text in standard ISO 8601 format. For a date, that is YYYY-MM-DD.

String output = ld.toString() ;

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.