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
基础教程推荐
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01