Edit after question was edited: The exception message that you get, Text '' could not be parsed at index 0
, means that you are trying to parse an empty string into a date-time, which fails since there was expected to be text in the string. How the empty string ends up there I cannot tell from your detached snippets.
java.time
IMHO you have put your question in the wrong way. It’s only in the simplest throw-away programs that you should want to convert a date and time from one string format to another. For any Spring Boot or other serious program you should not process dates and times as strings. You should parse them into proper datetime objects and only format them back when you need to give string output.
I recommend that you use java.time, the modern Java date and time API, for your date and time work. To parse your source string:
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendPattern(" (OOOO)")
.toFormatter();
String inputSource = "2020-04-14 00:00:00.0000000 (GMT-04:00)";
OffsetDateTime dateTime = OffsetDateTime.parse(inputSource, inputFormatter);
System.out.println(dateTime);
Output so far:
2020-04-14T00:00-04:00
It’s a bit longish. We could have created a DateTimeFormatter
directly from a format pattern string. The advantages of using the builder include:
- We are reusing two built-in formatters rather than building everything from scratch.
ISO_LOCAL_TIME
accepts a variable number of decimals on the seconds, so we are getting a more flexible formatter.
To format the date and time for output I am assuming (1) that you really wanted ISO 8601 format output since your example string resembles well, and (2) that you wanted the same point in time.
String formattedDateTime = dateTime.format(DateTimeFormatter.ISO_INSTANT);
System.out.println(formattedDateTime);
2020-04-14T04:00:00Z
The time has been changed to 04:00 UTC, the trailing Z
that you asked for meaning UTC. This is correct: when it’s 4 AM UTC, it’s only 00:00 (midnight) in a time zone at offset GMT-04:00 where the source string came from. You asked for three decimals on the seconds, but in ISO 8601 the decimals are optional when they are zero, so here they are not printed. If you need the string for data exchange with a system that requires ISO 8601, you’re set.
If you wanted the same wall-clock time, 00:00, even though it’s a different time zone, you can have that too:
String formattedDateTime = dateTime.withOffsetSameLocal(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_INSTANT);
2020-04-14T00:00:00Z
If you were serious about wanting the exact format that you mentioned, even though it disagrees with ISO 8601, use a home-made formatter:
DateTimeFormatter targetFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSX");
String formattedDateTime = dateTime.withOffsetSameLocal(ZoneOffset.UTC)
.format(targetFormatter);
2020-04-14 00:00:00.000Z
Links