我正在获取“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 的链接:日期/时间格式字符