2010-02-12 120 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