-2

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);
activelearner
  • 7,055
  • 20
  • 53
  • 94
  • 2
    It would be helpful to add a tag indicating what language you're using (Java?). I think you'll need to delete one of the existing tags. – Keith Thompson Feb 18 '22 at 05:24
  • 1
    I would suggest avoiding strings when storing this data, use localized string representations at output – Paul Maxwell Feb 18 '22 at 05:29
  • 3
    Do not longer use the outdated SimpleDateFormat and java.util.Date classes. Use the newer java.time API – Jens Feb 18 '22 at 05:39
  • 1
    Do you understand that your two strings, `2022-01-12T19:41:27.000+00:00` & `2022-01-12T19:41:27.000Z`, mean the very same thing? The `Z` on the end is a [standard](https://en.wikipedia.org/wiki/ISO_8601) abbreviation for `+00:00`, with both meaning an offset from UTC of zero hours-minutes-seconds. Furthermore, there is no need to display `.000` if the fractional second is zero. – Basil Bourque Feb 18 '22 at 06:05
  • 2
    `OffsetDateTime.parse( "2022-01-12T19:41:27.000+00:00" ).toString()` – Basil Bourque Feb 18 '22 at 06:09

1 Answers1

0

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
Jens
  • 67,715
  • 15
  • 98
  • 113