Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java dates zone format to simple format

is it possible to convert this kind of format in Java (probably ISO 8601) "2022-11-11T00:00:00" or this "2022-11-11T12:00:00+01:00" which comes as a string, to simple format "yyyy-mm-dd" with Date or Time kind of classes, or it should be done with string methods?

Example:

you receive this -> "2022-11-11T00:00:00"
you convert to this -> "2022-11-11"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you just have to

  • extract the date part (year, month of year and day of month) and
  • you are sure it will always be the first 10 characters of the Strings you receive

you could simply take the first 10 characters:

String toBeForwarded = "2022-11-11T00:00:00".substring(0, 10);

This line would store "2022-11-11" in toBeForwarded.


But if you need to calculate anything based on the values or maybe find out the day of week, you will be best adviced using java.time:

public static void main(String[] args) {
    // example input in ISO format
    String first = "2022-11-11T00:00:00";
    String second = "2022-11-11T12:00:00+01:00";
    // parse them to suitable objects
    LocalDateTime ldt = LocalDateTime.parse(first);
    OffsetDateTime odt = OffsetDateTime.parse(second);
    // extract the date from the objects (that may have time of day and offset, too)
    LocalDate firstDate = ldt.toLocalDate();
    LocalDate secondDate = odt.toLocalDate();
    // format them as ISO local date, basically the same format as the input has
    String firstToBeForwarded = firstDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
    String secondToBeForwarded = secondDate.format(DateTimeFormatter.ISO_LOCAL_DATE); 
    // print the results (or forward them as desired)
    System.out.println(firstToBeForwarded);
    System.out.println(secondToBeForwarded);
}

The output of this example is

2022-11-11
2022-11-11
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading