如何将给定为“20110912T220000”(NSString)的日期转换为NSDate

我正在以“20110912T220000”格式获取我的日历事件(在解析.ics文件时)的开始和结束日期。 如何将其转换为NSDate以添加为事件(EKEvent)的startDate属性。

如果有人知道请尽快帮助我。

你应该使用NSDateFormatter

请参阅数据格式指南 ( 日期和时间编程指南也可能很有趣)

Apple的问答中的技术说明中也对此进行了详细说明 。 请注意,对于此类情况,您应使用本技术说明中所述的特殊“en_US_POSIX”语言环境

 NSDateFormatter* df = [[NSDateFormatter alloc] init]; [df setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]]; [df setDateFormat:@"yyyyMMdd'T'HHmmss"]; NSDate* parsedDate = [df dateFromString:...]; 
 NSString *dateString = @"20110912T220000"; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; formatter.locale = locale; formatter.dateFormat = @"yyyyMMdd'T'HHmmss"; NSDate *date = [formatter dateFromString:dateString]; NSLog(@"date: %@", date); 

NSLog()输出: date: 2011-09-13 02:00:00 +0000

注意,NSLog以本地时区输出数据。
请注意日期格式中“T”周围的单引号。

以下是UTS的链接: 日期/时间格式字符