解析ISO 8601字符串本地日期时间,就像在UTC中一样 [英] Parsing an ISO 8601 string local date-time as if in UTC

查看:627
本文介绍了解析ISO 8601字符串本地日期时间,就像在UTC中一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,我需要以以下格式从String中创建一个Calendar对象:

In java I need to make a Calendar object from a String in the format:

yyyy-MM-dd'T'HH:mm:ss

此字符串将始终设置为GMT时间。所以这是我的代码:

This string will always be set as GMT time. So here's my code:

    public static Calendar dateDecode(String dateString) throws ParseException
{
    TimeZone t = TimeZone.getTimeZone("GMT");
    Calendar cal = Calendar.getInstance(t);
    date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date d = date.parse(dateString);
    cal.setTime(d);
    return cal;
}

然后:

Calendar cal = Calendar.getInstance();
    try
    {
        cal = dateDecode("2002-05-30T09:30:10");
    } catch (ParseException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    int month =  cal.get(Calendar.MONTH)+1;

我得到以下输出:

Timezone: GMT+00:00 date: 2002-5-30 time: 7:30:10

由于提供的时间是GMT而非CET,因此您可以看到错误。我认为发生的事情是它认为所提供的时间是在CET(这是我当前的时区),因此将时间从CET转换为GMT,因此从最终结果中减去两个小时。

Which is as you can see wrong since the time provided is in GMT and not CET. I think what happens is that it think the time provided is in CET (which is my current timezone) and therefore converts the time from CET to GMT and therefore deducts two hours from the final result.

有人可以帮我吗?

谢谢

Btw:我不希望出于不同的原因使用JodaTime。

Btw: I do not wish to use JodaTime for different reasons.

推荐答案

这里有一些代码可以帮助你在解析它们之前设置timzones:

Here is some code that could help you out with setting the timzones before parsing them:

// sdf contains a Calendar object with the default timezone.
Date date = new Date();
String formatPattern = ....;
SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);

TimeZone T1;
TimeZone T2;
....
....
// set the Calendar of sdf to timezone T1
sdf.setTimeZone(T1);
System.out.println(sdf.format(date));

// set the Calendar of sdf to timezone T2
sdf.setTimeZone(T2);
System.out.println(sdf.format(date));

// Use the 'calOfT2' instance-methods to get specific info
// about the time-of-day for date 'date' in timezone T2.
Calendar calOfT2 = sdf.getCalendar();

我发现的另一个类似问题也可能有所帮助:如何在Java和控件中设置默认时区日期存储在数据库上?

another similar question I found might help too: How to set default time zone in Java and control the way date are stored on DB?

编辑:

这是一个很棒的教程Java&日期: http://www.tutorialspoint.com/java/java_date_time.htm

Here is a great tutorial on Java & Dates too: http://www.tutorialspoint.com/java/java_date_time.htm

这篇关于解析ISO 8601字符串本地日期时间,就像在UTC中一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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