将具有 1 个时区的 NSString 日期转换为具有另一个时区的 NSDate 对象
嘿大家, 我需要使用 NSDateFormatter 将以下格式转换为新格式。我对此非常熟悉,但由于某种原因,我记不起此格式的正确格式信息:
“Fri, 25 Mar 2011 10:16:00 -0700”。
我尝试使用这种格式:'aaa, dd bbb YYYY HH:MM:SS ZHHMM' 但它不起作用,给了我过去的日期方式。
创建新日期时,我还需要将其转换为东部时区。它显示“+0000”,但是标准化后是什么?
任何帮助表示赞赏, 谢谢, 〜阿拉什
Hey everyone,
I need to convert the following format into a new format using NSDateFormatter. I am quite seasoned with this but for some reason I can't remember the correct formatting information for this foramt:
'Fri, 25 Mar 2011 10:16:00 -0700'.
I tried using this format:'aaa, dd bbb YYYY HH:MM:SS ZHHMM' but it doesn't work, gives me a date way in the past.
I also need to convert it into the Eastern Time Zone when creating a new date. It says '+0000' but what is that normalized to?
Any help appreciated,
Thanks,
~Arash
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常,当您获取这样的日期字符串时,您知道它们来自哪个区域设置,并且您将采用 NSDateFormatter,使用
setLocale:
设置其区域设置,使用设置其日期和时间格式code>setDateStyle:
和setTimeStyle:
,然后使用dateFromString:
。如果您因为不知道区域设置而无法做到这一点,那么您可以 使用 UNIX 函数:接下来,您要将 newDate“转换”为东部时间。我说“转换”是因为 NSDates 不包含任何有关时区的信息——它们只是表示为自 2001 年 1 月 1 日以来的秒数——所以转换的想法没有意义。当您打印出 NSDate 时,您会得到 UTC (+0000) 格式的它,但 NSDate 与该时区的关联并不比与其他时区的关联更大。
您想要做的是创建一个具有正确时区的 dateFormatter 并用它来输出日期:
Typically when you're getting date strings like that, you know what locale they're coming from, and you would take an NSDateFormatter, set its locale using
setLocale:
, set its date and time formatting usingsetDateStyle:
andsetTimeStyle:
and then usedateFromString:
. If you can't do that because you don't know the locale, then you can use the UNIX functions:Next, you want to "convert" newDate to Eastern Time. I say "convert" because NSDates don't contain any information about timezones—they're just represented as a number of seconds since January 1, 2001—so the idea of conversion makes no sense. When you print out an NSDate you get it in UTC (+0000), but an NSDate is no more associated with that timezone than with any other.
What you want to do instead is to create a dateFormatter with the right timezone and use it to output the date: