2012-12-07 26 views
1

我在UTC格式的字符串日期:轉換字符串的NSDate返回1年的區別

「2012-11-20T05:23:02.34」

現在我想的UTC NSDate對象爲此...並且我實現了此功能。

+ (NSDate *)utcDateFromString:(NSString *)string withFormat:(NSString *)format { 
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init]; 
    inputFormatter.timeZone =[NSTimeZone timeZoneWithAbbreviation:@"UTC"]; 
    [inputFormatter setDateFormat:format]; 
    NSDate *date = [inputFormatter dateFromString:string]; 
    [inputFormatter release]; 
    return date; 
} 

,並要求它像這樣...

NSDate* submittedDate =[NSDate utcDateFromString:submittedDateString withFormat:@"YYYY-MM-dd'T'HH:mm:ss.SS"]; 

但這返回NSDate的描述,因爲這..

2011-11-20 5時23分02秒+0000

現在,如果你發現有在時間一年的差距...誰能解釋爲什麼會出現這種情況..?

感謝您的幫助。

+0

「2012-11-20T05:23:02.34」中你的'T'是什麼? – sunkehappy

+0

我剛剛運行該代碼,它爲我提供了正確的答案。但是我把你的代碼粘貼到一個測試類中,並在該對象中創建了'utcDateFromString'方法,而不是NSDate上的Class方法。 – emrys57

+0

我剛剛重新嘗試了它,並在NSDate上實現了一個類別。而且這也起作用。抱歉! – emrys57

回答

5
在dateformmater

,使用yyyy代替YYYY

應該

NSDate* submittedDate =[NSDate utcDateFromString:submittedDateString withFormat:@"yyyy-MM-dd'T'HH:mm:ss.SS"]; 

這將解決這個問題。

在以下鏈接中,搜索YYYY。

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html

它採用YYYY指定年份組成。一個常見的錯誤是使用YYYY。 yyyy指定日曆年,而YYYY指定ISO年份周曆中使用的年份(「年份周」)。在大多數情況下,yyyy和yyyy產生相同的數字,但它們可能不同。通常你應該使用日曆年。

+0

謝謝..按照需要正常工作。 –

1

試試這個方法波紋管..

-(NSDate *)getUTCFormateDate:(NSString *)localDate withFormat:(NSString *)format 
{ 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:format]; 
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"]; 
    [dateFormatter setTimeZone:timeZone]; 
    NSDate *date = [dateFormatter dateFromString:localDate]; 
    return date;   
} 

,並使用像波紋管..

NSDate *dateHere = [[NSDate alloc]init]; 
    dateHere = [self getUTCFormateDate:@"2012-11-20T05:23:02.34" withFormat:@"yyyy-MM-dd'T'HH:mm:ss.SS"]; 
    NSLog(@"Date here %@",dateHere); 

和我得到的輸出是日期這裏2012年11月20日5時23分02秒+0000

看到我的另一個答案,返回字符串日期UTF格式..

convert NSstring date to UTC dateenter link description here

+0

@AnkitSrivastava嘗試這種方法和代碼工作完美看到輸出哥們.. :) –