将字符串转换为 GregorianCalendar

Convert a string to GregorianCalendar(将字符串转换为 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Month is not printed from a date - Java DateFormat(月份不是从日期打印的 - Java DateFormat)
java get week of year for given a date(java获取给定日期的一年中的一周)
Get the number of days, weeks, and months, since Epoch in Java(获取自 Java 中的 Epoch 以来的天数、周数和月数)
Is there a good way to get the date of the coming Wednesday?(有什么好方法可以得到即将到来的星期三的日期吗?)
Calendar view for Android GingerBread and before (APIlt;11)(Android GingerBread 及之前的日历视图 (API11))
How to save and retrieve Date in SharedPreferences(如何在 SharedPreferences 中保存和检索日期)