問(wèn)題描述
我有一個(gè)來(lái)自電子郵件標(biāo)題的字符串,例如 Date: Mon, 27 Oct 2008 08:33:29 -0700
.我需要的是一個(gè) GregorianCalendar 的實(shí)例,它將代表同一時(shí)刻.就這么簡(jiǎn)單——我該怎么做?
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?
對(duì)于最快的——這不會(huì)正常工作:
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)
因?yàn)樗鼘r(shí)區(qū)標(biāo)準(zhǔn)化為 UTC(或您的本地機(jī)器時(shí)間,取決于 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
.
推薦答案
如果可以的話(huà),我建議您查看 Joda Time 庫(kù).在核心平臺(tái)提供類(lèi)似功能的情況下,我通常反對(duì)使用第三方庫(kù),但我將其作為例外,因?yàn)?Joda Time 的作者也在 JSR310 背后,而 Joda Time 最終基本上會(huì)滾入 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/
所以無(wú)論如何,如果 Joda Time 是一個(gè)選項(xiàng),像這樣 應(yīng)該 工作:
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();
我希望這會(huì)有所幫助.
這篇關(guān)于將字符串轉(zhuǎn)換為 GregorianCalendar的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!