Home > OS >  How to change Timestamp String to "DD.MM.YYYY"?
How to change Timestamp String to "DD.MM.YYYY"?

Time:11-05

I have different format of strings that I need to convert to "DD.MM.YYYY".

"Thu, 3 Nov 2022 06:00:00 0100" has to be changed to "03.11.2022"
and
"01.11.2022 20:00:00" to "01.11.2022".

All the formats are in String.

I tried doing

String pattern="DD.MM.YYYY";
DateTimeFormatter formatter=DateTimeFormatter.ofPattern(pattern);

new SimpleDateFormat(pattern).parse("01.11.2022 20:00:00")

I have also tried doing the following

java.time.LocalDateTime.parse(
        item.getStartdatum(),
        DateTimeFormatter.ofPattern( "DDMMYYYY" )
    ).format(
        DateTimeFormatter.ofPattern("DD.MM.YYYY")
    )

But got the error :

Exception in thread "main" java.time.format.DateTimeParseException:
Text 'Sun, 30 Oct 2022 00:30:00  0200' could not be parsed at index 0

I tried doing the following as well

String pattern="DD.MM.YYYY";
DateFormat format = new SimpleDateFormat(pattern);
Date date = format.parse(01.11.2022 20:00:00);

However I am not getting the correct output. How can I get my desired output?

CodePudding user response:

Several things…

  • if you can use java.time, use it exclusively if possible (no SimpleDateFormat or similar legacy stuff)
  • a DateTimeFormatter can be used to parse and format Strings representing a datetime, if input and output format are different, you will need two different DateTimeFormatters
  • the Text 'Sun, 30 Oct 2022 00:30:00 0200' could not be parsed at index 0 due to your try to parse it with the pattern "DD.MM.YYYY", which is wrong on several levels:
    • the pattern seems to expect the String to start with a numerical representation of the day of month, but it starts with Thu, an abbreviation of the name of a day of week
    • the symbol D means day of year, a number between 1 and 366 (in leap years, 365 otherwise)
    • the symbol Y means week-based year

Read more about those symbols in the JavaDocs of DateTimeFormatter

You could do the following instead:

public static void main(String[] args) {
    // two example inputs
    String first = "Thu, 3 Nov 2022 06:00:00  0100";
    String second = "01.11.2022 20:00:00";
    // prepare a formatter for each pattern in order to parse the Strings
    DateTimeFormatter dtfInFirst = DateTimeFormatter.ofPattern(
                                        "EEE, d MMM uuuu HH:mm:ss x",
                                        Locale.ENGLISH
                                   );
    // (second one does not have an offset from UTC, so the resulting class is different)
    DateTimeFormatter dtfInSecond = DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm:ss");
    // parse the Strings using the formatters
    OffsetDateTime odt = OffsetDateTime.parse(first, dtfInFirst);
    LocalDateTime ldt = LocalDateTime.parse(second, dtfInSecond);
    // prepare a formatter, this time for output formatting
    DateTimeFormatter dtfDateOnlySeparatedByDots = DateTimeFormatter.ofPattern("dd.MM.uuuu");
    // extract the date part of each result of the parsing
    LocalDate firstResult = odt.toLocalDate();
    LocalDate secondResult = odt.toLocalDate();
    // and print it formatted using the output formatter
    System.out.println(first   " ---> "
                               firstResult.format(dtfDateOnlySeparatedByDots));
    System.out.println(second   " ---> " 
                                secondResult.format(dtfDateOnlySeparatedByDots));
}

Which will output the conversion results as follows:

Thu, 3 Nov 2022 06:00:00  0100 ---> 03.11.2022
01.11.2022 20:00:00 ---> 03.11.2022

The first formatter will need a Locale because of the presence of names (day of week & month). You cannot parse that using any exclusively numerical parser and the language / culture must match.

CodePudding user response:

This resource may be useful for formatting dates in Java https://www.digitalocean.com/community/tutorials/java-simpledateformat-java-date-format

  • Related