2013-08-28 75 views
0

我在我的應用程序中使用了NSDate概念。在我的一個課程中,我爲日期實例設置了[NSDate date],並將其用於下一課。它對我來說非常完美,但如果我使用那個日期,它會在5:30之前給我提供,所以我用NSDateFormatter來改變它,但是我得到了一個空響應。NSDate總是顯示爲空

NSLog(@"update date= %@",pullToRefreshManager_.pullToRefreshView.lastUpdateDate); 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"]; 
    [dateFormat setTimeZone:timeZone]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
    NSString *str=[NSString stringWithFormat:@"%@",pullToRefreshManager_.pullToRefreshView.lastUpdateDate]; 
    NSLog(@"Str== %@",str); 
    NSDate *date = [dateFormat dateFromString:[NSString stringWithFormat:@"%@",str]]; 
    NSLog(@"exact date= %@",date); 

控制檯我得到了把作爲

update date= 2013-08-28 07:34:23 +0000 
    Str== 2013-08-28 07:34:23 +0000 
exact date= (null) 
+0

這是我得到我的控制檯更新日期= 2013-08-28 07:34:23 +0000 Str == 2013-08-28 07:34:23 +0000 確切日期=(null) – KSR

+1

格式不匹配 - 向日期格式化程序添加「Z」。也就是說,我看不出有什麼理由將它轉換回日期對象。日期應該始終保持不變。只需使用正確的格式化程序*輸出*。 – Eiko

回答

0

的NSDate總是爲GMT。所以,你必須格式化日期,按您需要的timeZone。您可以將設備設置時區或可以使用日曆設置時區.. 更新: 使用此日期格式,而不是這個

[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"]; 
+0

我給了我的時區作爲UTC,它會給你當前的時區,但它不起作用 – KSR

+0

我們可以添加這個答案到一個ASKED EVERY DAY類別嗎?也許在'問一個問題'... ... –

0

在5號線

[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss +0000"]; 

和8號線 爲什麼使用的NSString與格式時已經str是字符串

NSDate *date = [dateFormat dateFromString:str]; 
+0

它顯示的結果,但它提前1小時我的系統時間@SARFARAZ可汗 – KSR

+0

@sumit Mundra請提醒它顯示的結果,但其提前1 HR我的系統時間 – KSR

+0

什麼是您的系統時區以及實際結果 –

0

因爲從「pullToRefreshManager_.pullToRefreshView.lastUpdateDate」獲取的日期可能與您的NSDateFormatter具有不同的日期格式,所以您將獲得空值。

要從字符串中獲取日期,我們需要datetring和NSDateFormatter的相同日期格式。

試試這個代碼:

NSDateFormatter *formatter1=[[NSDateFormatter alloc]init]; 
[formatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
formatter1.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
NSString *StrDate =[formatter1 stringFromDate:yourDate]; 
NSLog(@"String Date : %@",StrSunday); 

NSDate *date = [formatter1 dateFromString:StrDate]; 
NSLog(@"Date : %@",date); 
0

什麼的海峽價值?

我試過代碼

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"]; 
[dateFormat setTimeZone:timeZone]; 
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
NSLog(@"exact date= %@",[dateFormat stringFromDate:[NSDate date]]); 

的這一部分,它顯示的日期好。其他行中的某一行必須爲空。