I need to format a String that looks like this:
"2018-07-20 18:53:46.598000 +02:00:00"
into a DateTime object like this:
20/07/2018 (HH with Timezone applied):53:46
My approach has been:
String dateTimePattern = "dd/MM/yyyy HH:mm:ss";
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateTimePattern);
Date feUltModDateTime = dateTimeFormat.parse(feUltMod);
feUltMod = feUltModDateTime.toString();
But I'm getting a parse error:
java.text.ParseException: Unparseable date: "2018-07-20 18:53:46.598000 +02:00:00"
The above code will give you current Timestamp.Timestamp will provide better feasibilty
java.time
Output from this snippet is:
Generally you need two formatters for converting a date or date-time from one format to another: one that specifies the format to convert from and one that specifies the format to convert to.
A date-time object doesn’t have a format, so in that respect cannot be “like this”.
dateTimeWithTimeZoneApplied
in the above snippet is in the specified time zone, so has the hours adjusted. After converting to this time zone I have formatted into a string in the format you mentioned, in case you wanted this (I didn’t find it clear).I am using and recommending java.time, the modern Java date and time API. The date and time classes you were using,
Date
andSimpleDateFormat
, are long outdated and poorly designed, it’s not worth struggling with them. AlsoSimpleDateFormat
supports only milliseconds so can only work correctly with exactly 3 decimals on the seconds, not with the 6 decimals you have got.Link: Oracle tutorial: Date Time explaining how to use
java.time
.