NSDate真的很奇怪地转换 [英] NSDate is converting really strangely

查看:50
本文介绍了NSDate真的很奇怪地转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时间: 7:46 am

我想将其转换为NSDate.我这样做:

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"];

我的NSLog sr 我得到 1969-12-31 22:46:00 +0000

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?

推荐答案

不.这并不奇怪.NSDateConverter和NSDate只是在这里完成其预期的工作.

No. Its not strange. NSDateConverter & NSDate are just doing their intended job here.

您正在尝试将上午7:46" 转换为日期.它仅包含时间.字符串中未指定日期.如果未指定日期,则NSDate将默认为"1970-01-01" (Unix时代).因此,在转换字符串之后,您将获得日期"1970-01-01 7:46 am" .当您尝试在 NSLog 中显示此日期时,如果在调整timeZone偏移值后将显示日期.我猜你住在日本或韩国.您所在地区的偏移量可能是+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.

NSString *timeStr = @"7:46 am";
NSDateFormatter *f = [NSDateFormatter new];
[f setDateFormat:@"yyyy-MM-dd"];
NSString *dateStr = [f stringFromDate:[NSDate date]]; // dateStr = 2011-06-10
dateStr = [dateStr stringByAppendingFormat:@" %@", timeStr]; // dateStr = 2011-06-10 7:46 am 
[f setDateFormat:@"yyyy-MM-dd h:mm a"];
NSDate *sr = [f dateFromString:dateStr];

这篇关于NSDate真的很奇怪地转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆