Crash when converting string to date

﹥>﹥吖頭↗ 提交于 2019-12-24 07:43:33

问题


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

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