本文介绍了将字符串转换为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 wantDate 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时间库,如果这是一个选项。我通常反对使用第三方库,当核心平台提供类似的功能,但我把这个例外,因为Joda时间的作者也在后面的JSR310,Joda时间基本上将滚动到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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 21:24