How do I convert any Timestamp string to a single Format in Java


I want to convert the timestamps which are in different formats to one format
I want to convert following timestamps to single format

Time Stamp 1 : 2022-08-17T18:28:07.288496+05:30

Time Stamp 2 : 2022-10-27T13:17:47.987736542Z


yyyy-MM-dd'T'HH:mm:ss format

I have tried using DateFormatter of Java but it gives ParseException. Also used SimpleDateFormatter but was getting same exceptions.
Please suggest package or methods for the same.

Edit : Code I used for conversion

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(timestamp, formatter);

>Solution :

Using java.time here is a good idea compared to java.util.Date, Calendar and so on, but you have to use specific classes that match the information inside a String that represents a datetime or timestamp.

In your case, the String contains the following information:

  • year
  • month of year
  • day of month
  • hour of day
  • minute of hour
  • second of minute
  • fractions of second
  • offset from UTC

In particular, it’s the last one (offset from UTC) which makes your attempt fail because you (1) don’t consider it in the pattern of the DateTimeFormatter and (2) you use a class that cannot store it (LocalDateTime is not able / designed to hold information about a zone or an offset.

Having Strings with an offset can be stored in / parsed to OffsetDateTimes, if they are ISO formatted (as your examples are), you don’t even need to apply a custom DateTimeFormatter. You can simply call OffsetDateTime.parse(String).

You can then define a desired format for an output by creating a custom DateTimeFormatter and apply it in OffsetDateTime.format(DateTimeFormatter).

Here’s an example:

public static void main(String[] args) {
    // example Strings (your ones)
    String timestampOne = "2022-08-17T18:28:07.288496+05:30";
    String timestampTwo = "2022-10-27T13:17:47.987736542Z";
    // directly parse them to get instances of OffsetDateTime
    OffsetDateTime odtOne = OffsetDateTime.parse(timestampOne);
    OffsetDateTime odtTwo = OffsetDateTime.parse(timestampTwo);
    // prepare a formatter for your desired output
    DateTimeFormatter dtfOut = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss");
    // and print the values of the OffsetDateTimes formatted by that DateTimeFormatter



Leave a Reply Cancel reply