问题
In my app I DO NOT want to use the local time on the phone. I want to get the current time in GMT. To do this I have a date formatter with time zone set to GMT. I then do the following to get back the current time:
NSString *dateOne = [df stringFromDate:[NSDate date]];
NSDate *date1 = [df dateFromString:dateOne];
My app gets an EXC_BAD_ACCESS though on the dateFromString call. I checked the returned value from dateOne and it's format matches the dateformatters. What am I doing wrong? Is there a better way to do this?
Thanks
EDIT:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-mm-dd HH:mm:ss"];
回答1:
An easier way perhaps:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-mm-dd HH:mm:ss"];
NSTimeZone *tz = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:tz];
NSDate *date = [NSDate date];
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(@"Time now in GMT: %@",dateString);
来源:https://stackoverflow.com/questions/2353062/crash-when-converting-string-to-date