2013-02-22 60 views
3

我試圖使用NSDateFormatter更改爲山標準時間保存的日期,但它似乎並沒有工作。NSDateFormatter stringFromDate不返回字符串

它的輸出 「的currentdate:2013年2月22日23時二十零分二十秒+0000最新與日期格式:其它2000-01-01 07:00:00 +0000」 到控制檯。

它看起來像字符串沒有正確創建,但我似乎正在調用它,就像我看到它正常調用。

對此提出建議?

NSTimeZone * mtnTimeZ= [NSTimeZone timeZoneWithAbbreviation:@"MST"]; 

    NSDate *currentDate = [NSDate date]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
    [dateFormatter setTimeZone:mtnTimeZ]; 

    NSString * timeZ = [dateFormatter stringFromDate:currentDate]; 

    NSDate * newDate = [dateFormatter dateFromString:timeZ]; 
    NSLog(@"currentDate: %@ string With dateFormatter: %@ date made from string %@", currentDate, timeZ, newDate); 
+1

你沒有向我們展示NSLog的輸出 - 文本不同。仔細檢查你是否粘貼了CURRENT代碼(你是否按下保存?)以及該代碼的最新結果 - 某些內容不同步。 – 2013-02-22 23:45:06

+0

保存日期的格式是什麼?你發佈的代碼有點做作。你永遠不會從'NSDate'到'NSString'並返回到'NSDate',使用沒有設置特定格式的格式化程序。告訴我們您真正保存的內容以及將其轉換爲什麼內容。 – rmaddy 2013-02-22 23:51:38

回答

4

你需要設置樣式在它爲了工作指定日期和時間格式:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateStyle:NSDateFormatterFullStyle]; 
[dateFormatter setTimeStyle:NSDateFormatterFullStyle]; 

[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]]; 
NSString * dateCurrentTZ = [dateFormatter stringFromDate:[NSDate date]]; 

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"MST"]]; 
NSString * dateMSTZ = [dateFormatter stringFromDate:[NSDate date]]; 

NSLog(@"Date In Current Time Zone: %@", dateCurrentTZ); 
NSLog(@"Date In MST: %@", dateMSTZ); 

如果你要指定自己的格式:

NSDateFormatter Documentation

然後尋找基於iOS上&的Mac OSX版本 「固定格式」。你正在瞄準。

+0

從蘋果的文檔看來,格式化程序看起來像格式化程序將遵守給定的日期格式,但顯然不是。真的希望蘋果允許iOS使用OSX的dateWithCalendarFormat:timeZone方法來處理NSDate,它會讓事情變得更容易。 – PeejWeej 2013-02-23 22:11:46

1

嘗試把下面一行:

[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 

這樣的:

NSTimeZone * mtnTimeZ= [NSTimeZone timeZoneWithAbbreviation:@"MST"]; 

NSDate *currentDate = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 
[dateFormatter setTimeZone:mtnTimeZ]; 

NSString * timeZ = [dateFormatter stringFromDate:currentDate]; 

NSDate * newDate = [dateFormatter dateFromString:timeZ]; 
NSLog(@"currentDate: %@ string With dateFormatter: %@ date made from string %@", currentDate, timeZ, newDate); 
+0

日期格式應該默認爲區域設置的格式。 – 2013-02-22 23:46:34

+0

@HotLicks你必須指定一種格式。如果您的文檔沒有默認日期和時區樣式設置爲蘋果,所以需要指定它工作或定義固定格式。 – SAPLogix 2013-02-23 06:04:35

+0

我得到currentDate:2013-02-23 22:04:17 +0000字符串與dateFormatter:2013-02-23 03:04:17日期從字符串2013-02-23 10:04:17 +0000從您的代碼,不知道那裏有什麼, – PeejWeej 2013-02-23 22:04:58