将字符串转换为日期时崩溃 [英] Crash when converting string to date
本文介绍了将字符串转换为日期时崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用中,我不想在手机上使用当地时间.我想获得格林威治标准时间的当前时间.为此,我有一个时区设置为 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);
这篇关于将字符串转换为日期时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文