Java日期时间格式转换 [英] Java datetime format convert

查看:406
本文介绍了Java日期时间格式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

日期这里我的问题:

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

我知道该字符串是UTC时区。
我需要将此字符串转换为格式yyy-mm-dd'T'HH:mm:ssZ。



为此,我使用以下代码:

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

问题是这段代码是在服务器上运行的,时区为UTC + 1,其结果为我是这样的:

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

从初始时间起,它将从UTC时间戳(0000)中删除2个小时。


$ b $你能帮我解决一下吗?
谢谢。

解决方案

如果输出格式为UTC + 1,那么您应该使用outformatter而不是UTC。

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

另外,如果你不想要最后的+0000,那么删除Z

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


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.

解决方案

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");

这篇关于Java日期时间格式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆