問題描述
我有一個來自電子郵件標題的字符串,例如 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模板網!