2015-01-21 46 views
-1

我想從日期字符串中獲取一天中的時間。以下字符串應該返回上午12:00。NSDate從字符串轉換時返回nil

2010-08-24 00:00:00 +0000

但使用下面的代碼,我的NSDate對象返回,當它到達日誌聲明爲零。這裏有什麼問題?謝謝!

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"h:mma"]; 
NSDate *date = [df dateFromString:@"2010-08-24 00:00:00 +0000"]; 
NSLog(@"DATE: %@", [date description]); 

輸出:日期:(空)

+0

其因日期格式(字符串)的傳球doen't與之相匹配的日期格式....嘗試使用相同的日期格式.... [從字符串創建的NSDate]的 – 2015-01-21 02:24:25

+0

可能重複(http://stackoverflow.com/questions/9769190/create-a-nsdate-from-a-string) – 2015-01-21 02:29:32

+1

爲什麼沒有人會查閱文檔? – 2015-01-21 02:30:21

回答

1

試試這個:

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"YYYY-MM-dd hh:mm:ss ZZZZ"]; 
NSDate *date = [df dateFromString:@"2010-08-24 00:00:00 +0000"]; 
NSLog(@"DATE: %@", [date description]); 

乾杯!

測試在playgorund:

enter image description here

+0

謝謝,但我怎麼才能回到一天的時間? – Pheepster 2015-01-21 02:28:56

+0

[NSDate date]; //今天返回日期 – D33pN16h7 2015-01-21 02:29:29

+1

以上日期格式不正確。 – 2015-01-21 02:30:55

0

那麼你可以使用下面的過程在其給定的格式從日期字符串中提取時間

1.Get的NSDate對象。

2.使用所需的格式設置NSDateFormatter對象。

3.按要求的格式獲取日期字符串。

- (BOOL)application:(UIApplication *) 
application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    { 
    NSString *date = [self convertDate:@"2010-08-24 00:00:00 +0000" 
          fromFormat:@"yyyy-MM-dd HH:mm:ss ZZZZ" 
           toFormat:@"hh:mm a"]; 

    NSLog(@"DATE: %@", [date description]); 

    return YES; 
} 


- (NSString *)convertDate:(NSString *)inDateString 
      fromFormat:(NSString *)fromFormat 
       toFormat:(NSString *)toFormat 
{ 
    NSDateFormatter *dateFormatter = nil; 
    NSString *outDateString = nil; 
    NSDate *date = nil; 

    dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:fromFormat]; 

    date = [dateFormatter dateFromString:inDateString]; 

    [dateFormatter setDateFormat:toFormat]; 
    outDateString = [dateFormatter stringFromDate:date]; 

    return outDateString; 
} 
+0

你的日期格式不正確(儘管不像其他的不正確)。 – 2015-01-21 21:18:55