Search code examples
javajsoncodenameone

can you help me with converting this String that contains a date to a varialble of type date and format it?


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


Solution

  • Convert the String you have to a Date object, based on the input format...

    String dateString = "2023-04-20T00:00:00+02:00";
    SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
    Date date = inFormat.parse(dateString);
    

    Then use a different formatter to format the Date back to the desired String representation

    SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
    String outString = outFormat.format(date);
    System.out.println(outString);
    

    Which 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 the java.time API instead

    String dateString = "2023-04-20T00:00:00+02:00";
    LocalDateTime ldt = LocalDateTime.parse(dateString, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    String outString = ldt.format(DateTimeFormatter.ISO_DATE);
    System.out.println(outString);