'Convert string timestamp "yyyy-mm-dd'T'HH:mm:ss.SSS+ZZ:ZZ" to string timestamp "yyyy-mm-dd'T'HH:mm:ss.SSSZ" [duplicate]

For example, if I have the string timestamp 2022-01-12T19:41:27.000+00:00, I would like to get 2022-01-12T19:41:27.000Z.

I would like to ensure that I come with a solution that can in the future take string timestamps with the format "yyyy-mm-dd'T'HH:mm:ss.SSS+ZZ:ZZ" OR any other input format but will always return one standard output which is "yyyy-mm-dd'T'HH:mm:ss.SSSZ".

So far, I have come up with:

String ts = "2022-01-12T19:41:27.000+00:00";
Date date = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss.SSS+ZZ:ZZ", 
Locale.US).parse(ts);
System.out.println(date);

Timestamp tsp = new Timestamp(date.getTime()); 
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss.SSSZ");
String str = formatter.format(tsp);
System.out.println(str);

But I run into the following exception:

error: unreported exception ParseException; must be caught or declared to be thrown
Date date = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss.SSS+ZZ:ZZ", Locale.US).parse(ts);


Solution 1:[1]

You need a try- catch Block arround your code:

try {
    String ts = "2022-01-12T19:41:27.000+00:00";
    Date date = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss.SSS+ZZ:ZZ", 
    Locale.US).parse(ts);
    System.out.println(date);
    
    Timestamp tsp = new Timestamp(date.getTime()); 
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss.SSSZ");
    String str = formatter.format(tsp);
    System.out.println(str);
} catch (ParseException e){
     // handleException
}

or you have to extend your method with

throws ParseException

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jens