解析 ISO 8601 字符串本地日期时间,就像在 UTC 中

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

问题描述

限时送ChatGPT账号..

在 java 中,我需要从格式的字符串中创建一个日历对象:

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

您可以看到这是错误的,因为提供的时间是格林威治标准时间而不是欧洲中部时间.我认为发生的情况是它认为提供的时间是 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.

谁能帮我解决这个问题?

Could anyone help me with this?

谢谢

顺便说一句:出于不同的原因,我不想使用 JodaTime.

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

推荐答案

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

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中设置默认时区并控制日期在DB上的存储方式?

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 中一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:如何将公历字符串转换为公历? 下一篇:没有了

相关文章

最新文章