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
465 views
in Technique[技术] by (71.8m points)

java - Why is string to date and back to string resulting in two different strings?

My input string is:

"2016-06-13T14:20:09.866Z"

My output string is:

"2016-06-13T10:20:09.866-04"

Why are they different and how can I make it output in the same format as the input?

I convert from string to date:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH);
dateFormat.parse((String) date));

In a unit test, I convert the parsed date back into a string:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH);
dateFormat.format(date);
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The two dates are the same - only the format differs (one is 2pm UTC the other is 10am with an offset of -4 hours = 2pm UTC too).

So I suppose that what you want is to have the second string in UTC time zone too. In that case you can simply set the timezone of the second DateFormat:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

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

...