2013-04-02 20 views
-4

使用NSDateFormatter我想從「2013年1月21日11:55:00」更改日期格式「揚21,2013 5:30 AM「。如何更改日期類型爲「2013年1月21日5:30 AM」在iOS的

我試過下面的代碼。但它給出了一個不變的日期。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 

[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; 

NSDate *myDate = [NSDate dateWithTimeIntervalSinceReferenceDate:162000]; 
NSLog(@"%@",[dateFormatter stringFromDate:myDate]); 

上面的代碼提供了恆定的輸出:2001年1月3日上午02時30分〇〇秒

但在我的情況下,日期是動態的。

+0

如果你想輸出是動態的;您的輸入不能是靜態的。你通過'162000',這就是爲什麼你會得到不斷的輸出(我猜測時間會改變)。 – viral

+0

http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns – Chandu

回答

2
NSString *firstDate = @"2013-01-21 11:55:00"; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"yyyy'-'MM'-'dd HH':'mm':'ss"]; 
    NSDate *date = [dateFormatter dateFromString:firstDate]; 
    [dateFormatter setDateFormat:@"MMM d, yyyy h:mm a"]; 

    NSLog(@"Expected Result___ %@",[dateFormatter stringFromDate:date]); 
0

以及你得到恆定的輸出,因爲你給定輸入爲162000!

首先用它的格式,然後使用新的格式,從獲取的數據得到的字符串

使用這種輸出格式

@"MMM d, yyyy h:mm a" 

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init]; 
[dateFormatter setDateFormat:@"MMM d, yyyy h:mm a"]; 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]); 
1

試試這個

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 

[dateFormatter setDateFormat:@"MMM d, yyyy h:mm a"]; 

NSDate *myDate = [NSDate dateWithTimeIntervalSinceReferenceDate:162000]; 
NSLog(@"%@",[dateFormatter stringFromDate:myDate]; 
得到字符串中的日期

嘗試[NSDate date]而不是[NSDate dateWithTimeIntervalSinceReferenceDate:162000]

+0

我得到一個不變的「2001年1月3日2:30」。但我需要轉換爲動態。 –

+0

是的。當我使用[NSDate日期]時,我已經以所需格式獲得了今天的日期。無論如何,我可以動態地傳遞日期嗎? –

+0

你可以從字符串獲取你的日期.http://stackoverflow.com/questions/5604657/converting-nsstring-to-date –

相關問題