tl;dr
LocalDate.now().toString()
2021-08-23
Better to specify desired/expected time zone rather than rely implicitly on the JVM’s current default time zone.
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ).toString()
Details
LocalDate
If you want a date-only, use LocalDate
.
LocalDate ld = myZonedDateTime.toLocalDate() ;
The java.time.Date
class is terribly flawed, and should be avoided. The class was supplanted years ago by the modern java.time classes defined in JSR 310.
If you must use this class to interoperable with old code not yet updated to java.time, you can convert back and forth between the legacy classes and their replacements. Look for the new conversion methods added to the old classes.
java.util.Date
is not a date!
Understand that among its many flaws is the name of java.util.Date
. That class represents not a date but a moment in time as seen in UTC. So its replacement is java.time.Instant
, not LocalDate
.
java.util.Date d = java.util.Date.from( myZonedDateTime.toInstant() );
You asked:
How can I convert my string into a date and keep the date looking like the string?
Understand that none of these date-time classes are text. They have their own internally defined representation of a date-time value, not String
.
It sounds like you simply want text in standard ISO 8601 format (YYYY-MM-DD) for a date-only value. The java.time classes use the standard ISO 8601 formats by default when generating/parsing strings. So no need to define a custom formatting pattern.
String output = myZonedDateTime.toLocalDate().toString() ;
Date-time objects have no format, are not text
You asked:
Now how can I convert this String 2021-08-23 to a java.util.Date? I want the date to look exactly like the String
What you request makes no sense.
A java.util.Date
object is a date-time object, not text, not String
. A java.util.Date
object has no “format”.
Likewise, a java.time.ZonedDateTime
object is a date-time object, not text, not String
. A java.time.ZonedDateTime
object has no “format”.
And so too, a java.time.LocalDate
object is a date object, not text, not String
. A java.time.LocalDate
object has no “format”.
These date-time objects have a toString
method that generates text representing the embedded value using a default format. But you should not conflate that generated text with the original date-time object.