NSDate 的转换真的很奇怪
我有一个时间:7:46 am
我想将其转换为 NSDate。我这样做:
NSDateFormatter *f = [NSDateFormatter new];
[f setDateFormat:@"h:mm a"];
NSDate *sr = [f dateFromString:@"7:46 am"];
我 NSLog sr
并得到 1969-12-31 22:46:00 +0000
这些时间不一样。为什么这么乱?
I have a time: 7:46 am
I want to convert this to NSDate. I do this:
NSDateFormatter *f = [NSDateFormatter new];
[f setDateFormat:@"h:mm a"];
NSDate *sr = [f dateFromString:@"7:46 am"];
I NSLog sr
and I get 1969-12-31 22:46:00 +0000
Those times are not the same. Why is this so messed up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在尝试将
"7:46 am"
转换为日期。它仅包含时间。字符串中未指定日期。如果未指定日期,NSDate 将默认为"1970-01-01"
(Unix 纪元)。因此,转换字符串后,您将获得日期“1970-01-01 7:46 am”
。当您尝试在 NSLog 中显示此内容时,如果会在调整时区偏移值后显示日期。我猜你住在日本或韩国。您所在区域的偏移量可能是+09:00。因此它显示减去偏移量的日期。因此您会在日志中看到"1969-12-31 22:46:00 +0000"
。您可以使用以下方法将该时间设置为特定日期,可以是今天。
You are trying to convert
"7:46 am"
into a date. It contains only the time. No date is specified in the string. NSDate will default to"1970-01-01"
(Unix epoch) if no date is specified. So after you convert the string you will get the date"1970-01-01 7:46 am"
. When you trying to display this in NSLog, if will display the date after adjusting the timeZone offset value. I guess you live in Japan or Korea. Probably the offset of your region is +09:00. So it diaplays the date subtracting the offset. So you are seeing"1969-12-31 22:46:00 +0000"
in the log.You can use the following method to set that time to a particular date, may be today.
您没有提供日期或时区...假设您想表达“今天上午 7:42”,您可以使用以下代码:
myDate 的 NSLog 现在应该为您提供预期的输出(假设您想要 Today@7 :46am)。
You aren't providing the day or the timezone... assuming you want to express "today at 7:42am", you can use this code:
The NSLog of myDate should give you the expected output now (assuming you wanted today@7:46am).
由于您仅指定希望 NSDate 引用的时间,而不是日期,因此格式化程序使用默认日期(似乎非常接近 UNIX 纪元)。就像 Julio 所说,如果您希望 NSDate 引用该特定日期的时间,您也应该指定当前日期。
Since you are only specifying the time that you want the NSDate to refer to, and not the date, the formatter is using the default date (which seems to be very close to the UNIX epoch). Like Julio said, you should specify the current date as well, if you want the NSDate to refer to the time on that specific date.