2013-09-28 104 views
0

我有NSString的對象轉換成的NSDate的問題。這是我想做的事: 我從互聯網下載的RSS信息。我有整個NSXMLParser解析的消息。之後,我有一些部分或保存到特定的NSStrings。我想轉換元件(其包括RSS消息的發佈日期),以的NSDate,這樣我可以像一個日期對象上就可以執行某些操作(例如排序,顯示上的時鐘等)。這裏是我的長相喜歡的方式:NSDateFormatter dateFromString轉換

「星期三,2013年9月25日12時56分57秒GMT」

我試圖將其轉換爲NSDate的過程是這樣:

*//theString is NSString containing my date as a text 
NSDate *dateNS = [[NSDate alloc] init]; 
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
     [dateFormatter setDateFormat:@"EEE, dd MMM yyyy hh:mm:ss ZZZ"]; 
dateNS = [dateFormatter dateFromString:theString];* 

然而,在做了上面的代碼之後,dateNS總是顯示爲(null)。

我的問題很簡單:什麼是正確的方式來轉換NSString與日期格式化到NSDate對象?

順便說一句,我已經看到了網站 http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns 看來,有很多方法可以格式化特定的日期,但我找不到什麼,我做錯了。

+0

您需要24小時格式的「HH」小時。 – rmaddy

+0

OK,它現在的作品。我沒有設置時區和語言環境(順便說一句,我仍然不知道爲什麼我必須這樣做)。 – tom55

+0

但我又遇到了另一個問題:將我的日期從字符串轉換爲NSDate後,它會在3小時內移動,例如, 01.01.2013 11:30 - > 01.01.2013 14:30。爲什麼?是否因爲LocaleIdentifier錯誤(我在波蘭,我爲en_GB設置LocaleIdentifier - 我將它更改爲pl_PL時出現問題,TimeZone更改爲歐洲/華沙)。 – tom55

回答

0

你的問題是你的日期格式有不相同的堡壘爲您的日期字符串: 你應該設置日期格式相同的格式,與您的日期字符串

我的例子:

//將字符串轉換爲日期

NSString *beginString = @"Sat, 30 Dec 2013 14:45:00 EEST"; 
    //beginString = [beginString stringByReplacingOccurrencesOfString:@"EEST" withString:@""]; 
    //beginString = [beginString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 

    dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]]; 
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Helsinki"]]; 
    [dateFormat setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z"]; 
    dateFromString = [dateFormat dateFromString:beginString]; 

    //NSLog(@"Begin string: %@", beginString); 

    //NSLog(@"not formated: %@", dateFromString); 

    // Convert Date to string 

    [dateFormat setTimeZone:[NSTimeZone localTimeZone]]; 
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"ru_RU"]]; 
    [dateFormat setDateFormat:@"dd MMMM yyyy"]; 
    myStrDate = [dateFormat stringFromDate:dateFromString]; 
    [currentTitle setPubDate:myStrDate]; 
0

NSDate * dateNS = [[NSDate alloc] init];是沒用的,你不需要分配任何日期對象。

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"]; 
NSLog(@"%@", [dateFormatter dateFromString:@"Wed, 25 Sep 2013 12:56:57 GMT"]); 

輸出日期正確,你確定theString是不是nil

相關問題