i have this String that contains a date in this format "2023-04-20T00:00:00+02:00" and i want to convert it back to date in a format just like this 2023-04-20
i tried this code
String dateString=obj.get("eventDate").toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(dateString.substring(0, 10));
t.setEventDate(date);
but it gave me this output Wed Apr 26 01:00:00 WAT 2023 and it’s not what am looking for
2
Answers
Convert the
String
you have to aDate
object, based on the input format…Then use a different formatter to format the
Date
back to the desiredString
representationWhich will output
2023-04-20
Remember, date/time classes are a representation of the amount of time which has passed since some anchor point in time (ie the Unix Epoch), they do not have an intrinsic concept of "format", in fact the output of these classes should be consider debug information only, this is why we have formatters.
The modern approach
You should avoid making use of the
java.util
date/time classes, they are effectively deprecated, instead, you should be making use of thejava.time
API insteadtl;dr
String manipulation
Obviously you could simply manipulate the input string. Truncate after the first ten letters.
Or, split the string into pieces. Grab the first piece.
java.time
You could parse the input as a date-time value.
Use only the java.time classes for date-time work. Never use the terribly flawed legacy classes such as
Date
,Calendar
, andSimpleDateFormat
.To parse your particular input, use the
java.time.OffsetDateTime
class. Your input consists of three parts: a date, a time-of-day, and an offset from UTC of a number of hours and minutes. ToOffsetDateTime
class fully represents all three parts.In contrast, note that the
LocalDateTime
class seen in the other Answer cannot represent all three parts. That class represents only the first two of the three parts. So the use of that class there is misleading and confusing.After parsing, we can extract just the date portion, without the time of day, and without the offset.
Generate text to represent that date value, in standard ISO 8601 format.