Java日历&时区问题 [英] Java calendar & timezone issue

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

问题描述

在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解析之前: p>

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

这篇关于Java日历&时区问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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