2010-02-12 124 views
5

如何轉換NSString至NSDate ?如何將NSString轉換爲NSDate?

它必須在YYYY-MM-DD HH:MM:SS,當它從的NSString轉換成的NSDate格式這種格式

+0

這是http://stackoverflow.com/questions/1348965/how-to-read-a-nsdate-in-from-a-string的副本 – 2010-02-12 13:40:11

回答

11

使用NSDateFormatter的dateFromString:

NSString *dateStr = @"20100212"; 

// Convert string to date object 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"yyyyMMdd"]; 
NSDate *date = [dateFormat dateFromString:dateStr]; 

// Convert date object to desired output format 
[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; 
dateStr = [dateFormat stringFromDate:date]; 
[dateFormat release]; 
0

做出了的NSString擴展了點。

// Simple as this. 
date = dateString.dateValue; 

由於NSDataDetector,它承認了一大堆格式。

// Tested in GMT+1 (Hungary). 
@"2014-01-16" dateValue is <2014-01-16 11:00:00 +0000> 
@"2014.01.16" dateValue is <2014-01-16 11:00:00 +0000> 
@"2014/01/16" dateValue is <2014-01-16 11:00:00 +0000> 
@"2014 Jan 16" dateValue is <2014-01-16 11:00:00 +0000> 
@"2014 Jan 16th" dateValue is <2014-01-16 11:00:00 +0000> 
@"20140116" dateValue is <2014-01-16 11:00:00 +0000> 
@"01-16-2014" dateValue is <2014-01-16 11:00:00 +0000> 
@"01.16.2014" dateValue is <2014-01-16 11:00:00 +0000> 
@"01/16/2014" dateValue is <2014-01-16 11:00:00 +0000> 
@"16 January 2014" dateValue is <2014-01-16 11:00:00 +0000> 
@"01-16-2014 17:05:05" dateValue is <2014-01-16 16:05:05 +0000> 
@"01-16-2014 T 17:05:05 UTC" dateValue is <2014-01-16 17:05:05 +0000> 
@"17:05, 1 January 2014 (UTC)" dateValue is <2014-01-01 16:05:00 +0000> 

eppz!kit部分,從GitHub搶類別NSString+EPPZKit.h