将字符串转换为 GregorianCalendar

时间:2023-04-20
本文介绍了将字符串转换为 GregorianCalendar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个来自电子邮件标题的字符串,例如 Date: Mon, 27 Oct 2008 08:33:29 -0700.我需要的是一个 GregorianCalendar 的实例,它将代表同一时刻.就这么简单——我该怎么做?

I have a string from an email header, like Date: Mon, 27 Oct 2008 08:33:29 -0700. What I need is an instance of GregorianCalendar, that will represent the same moment. As easy as that -- how do I do it?

对于最快的——这不会正常工作:

And for the fastest ones -- this is not going to work properly:

SimpleDateFormat format = ... // whatever you want
Date date = format.parse(myString)
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date)

因为它将时区标准化为 UTC(或您的本地机器时间,取决于 Java 版本).我需要的是 calendar.getTimeZone().getRawOffset() 返回 -7 * milisInAnHour.

because it will normalize the timezone to UTC (or your local machine time, depending on Java version). What I need is calendar.getTimeZone().getRawOffset() to return -7 * milisInAnHour.

推荐答案

如果可以的话,我建议您查看 Joda Time 库.在核心平台提供类似功能的情况下,我通常反对使用第三方库,但我将其作为例外,因为 Joda Time 的作者也在 JSR310 背后,而 Joda Time 最终基本上会滚入 Java 7.

I'd recommend looking into the Joda Time library, if that's an option. I'm normally against using a third-party library when the core platform provides similar functionality, but I made this an exception because the author of Joda Time is also behind JSR310, and Joda Time is basically going to be rolled into Java 7 eventually.

http://joda-time.sourceforge.net/

所以无论如何,如果 Joda Time 是一个选项,像这样 应该 工作:

So anyway, if Joda Time is an option, something like this should work:

DateTimeFormatter formatter =
    DateTimeFormat.forPattern("your pattern").withOffsetParsed();
DateTime dateTime = formatter.parseDateTime("your input");
GregorianCalendar cal = dateTime.toGregorianCalendar();

我希望这会有所帮助.

这篇关于将字符串转换为 GregorianCalendar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:在Java中查找一个月中的天数 下一篇:匿名类混淆的动态构建

相关文章

最新文章