NSDate is converting really strangely
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 a开发者_运维百科re not the same. Why is this so messed up?
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];
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).
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.
精彩评论