2012-11-02 56 views
1

我有一個web服務,它以以下方式返回我的日期。將日期轉換爲正確的格式

Wed Oct 31 11:59:44 +0000 2012 

但我想它給它放回這樣

31-10-2012 11:59 

我知道它應該有一個NSDateFormatter來完成。但是我現在不知道如何以正確的方式實施它。

我有這樣的事情。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
    [dateFormatter setDateFormat:@"dd/MM/yyyy"]; 
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+0:00"]]; 
    NSDate *date = [dateFormatter dateFromString:[genkInfo objectForKey:DATE]]; 

有人能幫助我嗎?

親切的問候。此刻

代碼

NSDateFormatter *f = [[NSDateFormatter alloc] init]; 
    [f setDateFormat:@"E MMM d hh:mm:ss Z y"]; 
    NSDate *date = [f dateFromString:@"Wed Oct 31 11:59:44 +0000 2012"]; 
    NSDateFormatter *f2 = [[NSDateFormatter alloc] init]; 
    [f2 setDateFormat:@"dd-MM-y hh:mm"]; 
    [f2 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 
    NSString *date2 = [f2 stringFromDate:date]; 

Webservice的佈局

"text": "KRC Genk | Zaterdag is er opnieuw een open stadiontour http://t.co/tSbZ2fYG", 
"created_at": "Fri Nov 02 12:49:34 +0000 2012" 
+0

希望它能解決您的問題。 http://stackoverflow.com/a/13024673/1111384 – iCreative

+0

很奇怪。它是相同的代碼。嘗試清理你的項目,並再次運行 –

+0

@RamyKfoury感謝您提前給予的幫助,但清理了我的項目並再次運行,但仍然沒有成功。我將編輯我的web服務如何外觀的問題。 – Steaphann

回答

2

第1步:創建一個NSDateFormatter由格式設置爲你的字符串從服務器轉換爲一個NSDate對象「服務器字符串」的格式

NSDateFormatter *f = [[NSDateFormatter alloc] init]; 
[f setDateFormat:@"E MMM d hh:mm:ss Z y"]; 
NSDate *date = [f dateFromString:@"Wed Oct 31 11:59:44 +0000 2012"]; 

第2步:創建另一個NSDateFormatter與所需的輸出字符串,並使用新的NSDate對象轉換爲字符串對象的新NSDateFormatter

NSDateFormatter *f2 = [[NSDateFormatter alloc] init]; 
[f2 setDateFormat:@"dd-MM-y hh:mm"]; 
[f2 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 
NSString *s = [f2 stringFromDate:date]; 

desiredformat = s; 

附:我不知道F格式的,檢查此鏈接 http://www.developers-life.com/nsdateformatter-and-uifont.html

+0

代碼會很好,謝謝 – Steaphann

+0

mmm s返回null。 – Steaphann

+0

它應該是MMM,而不是mmm。 – hwaxxer

0

沒有與您的格式字符串解析原始日期的幾個問題。而區域設置不正確。無需設置時區。這將從提供​​的日期/時間字符串進行處理。

NSDateFormatter *f = [[NSDateFormatter alloc] init]; 
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; 
[f setLocale:posix]; 
[f setDateFormat:@"EEE MMM dd hh:mm:ss Z yyyy"]; 
NSDate *date = [f dateFromString:@"Wed Oct 31 11:59:44 +0000 2012"]; 

您要使用的en_US_POSIX區域每當你解析(或格式化)固定格式日期不是來自或用戶。不要使用en_US_POSIX語言環境向用戶顯示日期或時間。