Home > other >  Java dates zone format to simple format
Java dates zone format to simple format

Time:05-04

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"

CodePudding user response:

Recommended way: java.time

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

Not recommended, but possible: String manipulation

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.

  • Related