Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

date - Java datetime format convert

date here my problem:

String datetime = "2012-03-24 23:20:51";

I know that that string is in UTC timezone. I need to convert this string to format "yyy-mm-dd'T'HH:mm:ssZ".

To do this I'm using following code:

    SimpleDateFormat inFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    inFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date inDate = inFormatter.parse(datetime);
    SimpleDateFormat outFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    outFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    String output = outFormatter.format(inDate);

The problem is that this code is running on a server with timezone UTC+1 and the result it gave me is this:

output = "2012-03-24T21:20:51+0000"

It removes 2 hours from the initial time and puts the UTC timestamp (0000).

Can you please help me solving this? Thank you.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If the output format is UTC+1 then you should use that in the outformatter instead of UTC.

outFormatter.setTimeZone(TimeZone.getTimeZone("UTC+01:00"));

Also, if you don't want the +0000 at the end then remove the Z

SimpleDateFormat outFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...