2011-01-13 105 views
5

我一直在绞尽脑汁,没有运气。可能有人请告诉我如何将这个字符串转换:如何将一个NSString转换为NSDate?

“2011-01-13T17:00:00 + 11:00”

成的NSDate?

+1

检查了这一点:http://stackoverflow.com/questions/1353081/nsstring-to-nsdate – lms 2011-01-13 13:04:42

回答

20

unicode日期格式文档是here

而且,对于你的情况,你可以试试这个:

// original string 
NSString *str = [NSString stringWithFormat:@"2011-01-13T17:00:00+11:00"]; 

// convert to date 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
// ignore +11 and use timezone name instead of seconds from gmt 
[dateFormat setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss'+11:00'"]; 
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Melbourne"]]; 
NSDate *dte = [dateFormat dateFromString:str]; 
NSLog(@"Date: %@", dte); 

// back to string 
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init]; 
[dateFormat2 setDateFormat:@"YYYY-MM-dd'T'HH:mm:ssZZZ"]; 
[dateFormat2 setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Melbourne"]]; 
NSString *dateString = [dateFormat2 stringFromDate:dte]; 
NSLog(@"DateString: %@", dateString); 

[dateFormat release]; 
    [dateFormat2 release]; 

希望这有助于。

1

你尝试这个

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
NSDate *dateT = [dateFormatter dateFromString:str]; 

干杯

+0

你好,是的,我有这个 NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; NSDate * dateT = [dateFormatter dateFromString:@“2011-01-13T17:00:00 + 11:00”]; NSLog(@“date From string:%@”,dateT); This returns(null) – jennas 2011-01-13 12:58:17

+0

这将帮助你http://stackoverflow.com/questions/4655199/how-to-set-date-format-retrieved-from-uidatepicker/4655297#4655297 – Aditya 2011-01-13 13:01:44

+0

这是错的,不工作根本就没有日期。 – 2013-10-18 07:45:05

3

穿上这部分用单引号,并检查Unicode的文档的格式完全相同。在我的情况下,我有类似的东西,我这样做:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
     [dateFormat setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss.SSS"]; 

再次,不完全相同,但你明白了。另外,在字符串和nsdates之间来回转换时要小心时区。

同样,在我的情况,我用:

[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]]; 
+0

嗨,即时设置[NSTimeZone systemTimeZone]这是正确的区域。下面还是返回null血腥的东西![dateFormatter setDateFormat:@“yyyy-MM-dd'T'hh:mm:ssSSS”]; – jennas 2011-01-13 13:30:00

0

您可以查看TouchTime。

https://github.com/jheising/TouchTime

它是5.4中用于Cocoa和iOS的真棒strtotime函数的直接端口。它将采用任意格式的日期或时间字符串并将其转换为NSDate。

希望它的作品,并享受!

0

尝试使用这个启用cocoapods的项目。有许多增加的功能可能也需要。

“扩展Cocoa的NSDate类的一个类,带有一些便利功能。”

https://github.com/billymeltdown/nsdate-helper

下面是他们的第一个例子:

NSDate *date = [NSDate dateFromString:@"2009-03-01 12:15:23"];