NSDate is converting really strangely

不羁岁月 提交于 2019-12-08 06:07:24

问题


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?


回答1:


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

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



回答2:


You aren't providing the day or the timezone... assuming you want to express "today at 7:42am", you can use this code:

NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:7];
[comps setMinute:42];
NSDate *myDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[comps release];

The NSLog of myDate should give you the expected output now (assuming you wanted today@7:46am).




回答3:


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.



来源:https://stackoverflow.com/questions/6301705/nsdate-is-converting-really-strangely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!