将字符串转换为日期时崩溃
问题描述:
在我的应用中,我不想在手机上使用当地时间.我想获得格林威治标准时间的当前时间.为此,我有一个时区设置为 GMT 的日期格式化程序.然后我执行以下操作以获取当前时间:
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];
我的应用程序在 dateFromString 调用中获得了 EXC_BAD_ACCESS.我检查了 dateOne 的返回值,它的格式与 dateformatters 匹配.我究竟做错了什么?有没有更好的方法来做到这一点?
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?
谢谢
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-mm-dd HH:mm:ss"];
答
也许更简单的方法:
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);