问题
I am using a SimpleDateFormat
and I am getting results from two different sources. One source uses the format "yyyy-MM-dd HH:mm:ss"
, while the other uses "yyyy-MM-ddTHH:mm:ssZ"
. I am not interested in obtaining the time zone ('Z' value) from the second format, is there a way I can obtain these times without using different format strings? Something that will ignore the middle character as well as the characters after 'ss'
.
回答1:
The cleanest and clearest solution is if you can separate the strings from the two sources and use an appropriate formatter for each.
Another approach that you might consider is “taking a taste” to determine which format you’ve got and pick the formatter based on that. For example if (result.contains("T") && results.endsWith("Z"))
.
Since you asked about avoiding different format strings, that is possible too:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd[ ]['T']HH:mm:ss[X]");
System.out.println(LocalDateTime.parse("2015-11-06 21:23:18", formatter));
System.out.println(LocalDateTime.parse("2018-08-25T08:18:49Z", formatter));
Output from this snippet is:
2015-11-06T21:23:18 2018-08-25T08:18:49
I recommend you avoid the SimpleDateFormat
class. It is long outdated and notoriously troublesome. Instead I recommend you use java.time, the modern Java date and time API. It’s so much nicer to work with.
The square brackets denote optional parts of the format. The format will accept also a string that has both a space and a T
in the middle, and one that hasn’t got any of them. For most purposes I suggest that we can live with that. If you really insist, I believe you can play a similar trick with SimpleDateFormat
, it accepts square brackets too.
I am not happy about ignoring the offset in the second string and doing that only because you said you wanted to. I’d clearly prefer the following just slightly longer solution:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd[ ]['T']HH:mm:ss[X]")
.withZone(ZoneOffset.UTC);
System.out.println(OffsetDateTime.parse("2015-11-06 21:23:18", formatter));
System.out.println(OffsetDateTime.parse("2018-08-25T08:18:49Z", formatter));
Output is the same, only now with offset:
2015-11-06T21:23:18Z 2018-08-25T08:18:49Z
Link: Oracle tutorial: Date Time explaining how to use java.time
.
回答2:
I know this is old but for the date with the T in the middle and the time zone at the end "2018-08-24T08:02:05-04:00" use the following in your simpledateformat: "yyyy-MM-dd\'T\'HH:mm:ssX"
来源:https://stackoverflow.com/questions/33575947/simpledateformat-ignore-characters