我讀了所有關於NSDate
和NSDateFormatter
但沒有任何解決我的問題。我需要獲取當前日期,並在NSDate對象中使用此日期,但是當我這樣做時,我的小時總是帶有+2小時。即時通訊做這樣的事情:NSDate和NSDateFormatter不是我當前的本地或字符串日期
NSDateFormatter * dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setLocale:[NSLocale currentLocale]];
[dateformatter setDateFormat:@"yyyy-mm-dd HH:mm:ss"];
//NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
//NSLog(@"timezone local = %@",localTimeZone);
//[NSTimeZone timeZoneWithAbbreviation:@"BRST"];
NSString * current = [dateformatter stringFromDate:[NSDate date]];
NSLog(@"current = %@",current); // Cool this is my current date!
NSDate *thedate = [dateformatter dateFromString:current];
NSLog(@"date = %@",thedate);// NO! my hours is wrong
我需要添加我的當前日期NSDate
,並且還需要添加一個NSDate
一個字符串(與方法stringFromDate
)。字符串示例:2013-01-21 17:05:17。當通過返回NSDate的方法stringFromDate
傳遞這個字符串時,我打印NSDate並給我這個錯誤的日期:2013-01-21 19:05:17 +0000。
只是簡歷:
需要添加到我的NSDate的當前日期,也需要用
NSString
加入到NSDate
像2013年1月21日17時05分17秒。我目前的本地是Brasil /Sãopaulo,而NSTimerZone abreviation是BRST。
當你實例化一個NSDate對象時,它默認設置爲當前日期。你的日期是正確的。問題是,當你通過它的描述方法顯示它的值(當你把它作爲@「%@」登錄時,這就是所謂的),你可能會用不同的語言環境來使用它,這就是爲什麼你認爲它不是正確。 但是你可以嘗試用格式化程序重新格式化,你會看到你得到了相同的字符串(這將是你的預期)。 所以一般的想法是顯示NSDate始終使用NSDateFormatter而不是它的描述消息,所以你不會感到困惑。 – 2013-02-14 17:51:28