Crash when converting string to date

2019-07-26 21:35发布

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条回答
手持菜刀,她持情操
2楼-- · 2019-07-26 22:07

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);
查看更多
登录 后发表回答