Convert a string to GregorianCalendar(将字符串转换为 GregorianCalendar)
问题描述
我有一个来自电子邮件标题的字符串,例如 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将字符串转换为 GregorianCalendar


- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 获取数字的最后一位 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 转换 ldap 日期 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01