Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
897 views
in Technique[技术] by (71.8m points)

parsing - Java Unparsable date

I have a string with the format: String dateString = "2014-03-17T20:05:49.2300963Z"

Trying this:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SSSX");
Date date = df.parse(dateString);

Results in an Unparsable date exceptioon.

The docs: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html indicate that X is used with ISO 8601 when a single letter is used for the TimeZone.

EDIT Re-reading the docs, I've switched up the SimpleDateFormat a little:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
dateString = dateString.replace("Z", "");

I take out the Z because I know the timezone, use H instead of k and add a couple more S for giggles.

Now the time is parsing, but incorrectly. Date is accurate, Time seems to be random.

EDIT 2 The problem is that java only allows millisecond accuracy, so 2300963 is being interpreted as 2300 seconds and 963 milliseconds. I'll need to format my string a little differently to get this to work.

EDIT 3 Turns out you can't have a fractional part of a second in Java. It has to be truncated to milliseconds. I ended up using a type made available to me by my database, but the general solution is to truncate the fractional part of the second to millisecond. I'll post example code of how to do that as an answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to provide as many S as you have in your date String. In this case, 7

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SSSSSSSX");

This is required because, otherwise, the DateFormat doesn't know where the milliseconds end and where the time zone starts.


Note also, that

2300963

as a millisecond value means 2300 seconds and 963 milliseconds. Why do you have it that way? Why aren't those seconds part of the value in their corresponding position? When the DateFormat parses it, they will be added.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...