NSDateFormatter dateFrom 带纪元的字符串
我正在尝试解析仅包含年份的日期,例如 公元前145年或公元前123年 进入 NSDate 对象 - 到目前为止还没有取得多大成功。
NSDateFormatter f = [[NSDateFormatter alloc]init];
[f setTimeZone:[NSTimeZone systemTimeZone]];
[f setFormatterBehavior:NSDateFormatterBehaviorDefault];
[f setDateFormat:@"y GG"];
date = [f dateFromString:yearString];
yearString 包含例如 145 或 123 BC
结果是:
如果我在 dateFormat 中指定时代 (GG),我会得到 nil。
如果我只在 setDateFormat 中指定年份 (y) 并且我解析的年份是 145,我会得到一个日期,但它实际上是 145 之前 1 小时。
两个问题:
1. 将带有时代后缀的年份解析为 NSString 的正确方法是什么? 2. 为什么会出现时差?
I am trying to parse dates that only consist of years like
145 or 123 BC
into NSDate Objects - with not much success so far.
NSDateFormatter f = [[NSDateFormatter alloc]init];
[f setTimeZone:[NSTimeZone systemTimeZone]];
[f setFormatterBehavior:NSDateFormatterBehaviorDefault];
[f setDateFormat:@"y GG"];
date = [f dateFromString:yearString];
yearString contains e.g. 145 or 123 BC
The results are:
I get nil if I specify the era (GG) in the dateFormat.
If I just specify the year (y) in setDateFormat and the year I parse is 145 I get a date, but it is actually 1 hour before 145.
Two questions:
1. What is the proper way to parse years with era suffixes into NSStrings?
2. Why do I get the hour difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的时区可能是 GMT+1。因此,您实际上并没有提前一小时获得日期,但是(因为您的日期格式化程序设置为您的时区),您将日期解析为
145-01-01 00:00 +0100
。现在,当您使用-[NSDate description]
输出日期时,它将为您提供 GMT 中的等效时间点,即144-12-31 23:00 +0000
。Your time zone is probably GMT+1. So you're not actually getting a date one hour earlier but (because your date formatter is set to your time zone), you are parsing the date as
145-01-01 00:00 +0100
. When you now output the date with-[NSDate description]
, it will give you the equivalent point in time in GMT, which is144-12-31 23:00 +0000
.如果您不包含纪元后缀(如“145”),您将从格式化程序中得到
nil
。将其设为“公元 145 年”,我想您会发现它有效。日期格式组件不是可选的 - 您必须匹配整个模式。You'll get
nil
from the formatter if you don't include an era suffix, as is the case for '145'. Make it '145 AD', and I think you'll find it works. The date format components aren't optional — you have to match the whole pattern.我自己刚刚遇到这个问题。 @OleBergmann 对问题第二部分的回答是正确的,但是尽管 @bosmac 对问题主要部分的回答在技术上是正确的,但它并不是很有帮助。
这就是我所做的......
或者,更简洁......
Just came across this problem myself. @OleBergmann's answer to the second part of your question is correct, but although @bosmac's answer to the main part of your question is technically right, it's not very helpful.
Here's what I did...
Or, more tersely...