2010-02-28 91 views
1

在我的應用程序中,我不想在手機上使用本地時間。我想在格林尼治標準時間獲得當前時間。要做到這一點,我有一個日期格式化與時區設置爲GMT。然後我做了以下找回當前時間:將字符串轉換爲日期時崩潰

NSString *dateOne = [df stringFromDate:[NSDate date]]; 
NSDate *date1 = [df dateFromString:dateOne]; 

我的應用雖然得到一個EXC_BAD_ACCESS在dateFromString通話。我檢查了dateOne返回的值,它的格式與dateformatters匹配。我究竟做錯了什麼?有一個更好的方法嗎?

感謝

編輯:

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"yyyy-mm-dd HH:mm:ss"]; 
+0

是什麼控制檯說? – kennytm 2010-03-01 08:17:54

+0

您正在使用「mm」作爲月份。用'MM'代替。[df setDateFormat:@「yyyy-MM-dd HH:mm:ss」]; – 2012-10-13 11:19:11

回答

0

一種更簡單的方式也許:

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);