Reputation: 4058
I am trying to parse following date time string
2018-01-30T23:59:59.000
I am not able to understand which standard format it is like UTC or ISO_8601
while parsing in the following manner:
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS:MS");
Date date = null;
try {
date = sdf.parse("2018-01-30T23:59:59.000");
} catch (ParseException e) {
e.printStackTrace();
}
But It is throwing following exception:
java.text.ParseException: Unparseable date: "2018-01-30T23:59:59.000"
Any help is appreciated.
Upvotes: 1
Views: 9570
Reputation: 28269
See the doc of SimpleDateFormat and try this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Upvotes: 3
Reputation: 86232
LocalDateTime dateTime = LocalDateTime.parse("2018-01-30T23:59:59.000");
System.out.println(dateTime);
This prints:
2018-01-30T23:59:59
Your string is in ISO 8601 format. UTC or Coordinated Universal Time is not a format, it is a standard time used to define the time the rest of use in our respective time zones.
The date-time classes you were using, SimpleDateFormat
and Date
, are long outdated and the former in particular notoriously troublesome. I recommend that you instead use java.time
, the modern Java date and time API. It is so much nicer to work with.
A LocalDateTime
is a date with time of day and without time zone or offset from UTC. Its one-argument parse
method parses ISO 8601, which is why no explicit formatter is needed.
Your format pattern string has a number of issues to it. Which is one reason why you should appreciate the above solution without any explicit formatter. The first thing that goes wrong is: Your format pattern string has a colon, :
, between seconds and milliseconds, whereas your date-time string has a dot, .
. This is why you get the exception.
However, fixing this, your code yields the following Date
:
Sun Dec 31 23:00:00 CET 2017
It’s one month off from the expected, and the minutes and seconds are missing. Because:
YYYY
is for week-based year and only useful with a week number. You need lowercase yyyy
for year.DD
is for day of year. You need lowercase dd
for day of month.MM
for month. Trying the same again for minutes won’t work. Maybe you can guess by now: it’s lowercase mm
.ss
for seconds.MS
for milliseconds is interesting. SimpleDateFormat
takes it as M
for month (which we’ve already had twice before) and uppercase S
for millisecond. Instead you needed uppercase SSS
for the three digits of milliseconds.java.time
.Upvotes: 2
Reputation: 11638
You need to escape the literal T
:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:SS");
See This SO Answer for more examples
Update: Your string is in the format
yyyy-MM-dd'T'HH:mm:ss.SSS
but you are trying to parse it with a completely uppercase format string.
This does not do what you want it to do and you should read the documentation on SimpleDateFormat and the format string placeholders
Upvotes: 2