2011-10-14 107 views
0

我有一個字符串,其中有日期字段。我將字段作爲NSString存儲在我的數據庫中,如2011-12-07 21:15:00 +0000。如何更改字符串的NSDateFormatter

我使用下面的代碼,以獲得從日期格式字符串的日期,如:

NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease]; 
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"]; 

我想在時間格式爲hh一個上述日期格式,但它總是給空。 我的代碼:

NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"]; 

    NSDateFormatter *timeFormat = [[[NSDateFormatter alloc] init] autorelease]; 
    [timeFormat setDateFormat:@"hh a"]; 

    [dateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease] ]; 
    NSDate *date1 = [dateFormat dateFromString:startSection]; 

    NSLog(@"Date 1 : %@", date1); 


    [timeFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease] ]; 
    NSDate *time1 = [timeFormat dateFromString:startSection]; 
    NSString *strSection2 = [NSString stringWithFormat:@"%@", time1]; 
    NSLog(@"Time 1 : %@", strSection2); /// always null at this place. 

我不知道我在做什麼錯在這裏。有人能幫我在這裏嗎?

+0

嘿!你試過我的建議嗎?對你起作用嗎? – Phlibbo

+0

嗨Phlibbo.Thanks你的幫助。但我的看法不僅僅是看日期。我必須對我必須編寫代碼的字符串進行排序。 – lifemoveson

+0

對不起,但我不明白你的最後一條評論的一個字:/ – Phlibbo

回答

0

當您運行此代碼時顯示輸出會很有幫助。但是如果我不得不猜測你在時間格式部分做錯了什麼。我建議你從數據庫字符串您的日期,使用日期格式,你擁有它,而在這一點代碼: (這我假設的作品)上面的代碼後

[dateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease] ]; 
NSDate *date1 = [dateFormat dateFromString:startSection]; 

NSLog(@"Date 1 : %@", date1); 

開關齒輪而做到這一點,而不是太讓你的時間,所需的格式的字符串:

[timeFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease] ]; 
NSString * time = [timeFormat stringWithDate:date1]; 
NSLog(@"Time 1 : %@", time); 
+0

我相信我可以做到這一點,並在NSString中獲得timeFormat的價值。但我擔心的是,當我在nsstring上排序日期時會給出錯誤的輸出。因此,我期待改變它NSDate,使日期的排序是正確的。 – lifemoveson

+0

根據我上面創建的處理字符串進行排序,或者將您的排序設置爲您希望使用NSDate排序的內容。日期是日期,日期格式對NSDate沒有影響。我無法猜測你的排序是什麼意思,但就日期而言,我認爲升序和降序將是唯一有意義的方法,因此您不需要執行任何格式化。如果您希望單獨按小時排序,請在格式化後使用該字符串。 – EricLeaf

+0

我已經將小時單獨用作字符串,然後添加到數組中,發現它在運行查詢時排序不正確。我得到以下輸出:Array:{10AM, 11AM, 8AM}如何更改以下數組排序?我目前正在使用sortedArrayUsingSelector:@selector(compare :)。 – lifemoveson

0

您的日期去2011-12-07 21:15:00 +0000,而你的formatString的推移@"yyyy-MM-dd HH:mm:ss.S"ss.S是這裏的問題。使它@"yyyy-MM-dd HH:mm:ss +S",它會工作。

關於時間格式,我不確定你在做什麼。你顯然將相同的字符串傳遞給它(startSection),它甚至不會接近hh a

更新:哦,如果我沒有弄錯,格式如下this conventions這意味着你可能尋找Z和不S.