我正在尝试将字符串转换为 NSDate 对象。我正在使用以下代码进行转换:
NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];
NSTimeZone *tz = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormat setDateFormat:@"M/d/yyyy HH:mm:ss a"];
[dateFormat setTimeZone:tz];
NSDate * dtEventStart = [dateFormat dateFromString:@"1/7/2013 6:30:00 AM"];
NSDate * dtEventEnd = [dateFormat dateFromString:@"1/7/2013 8:45:00 PM"];
NSLog(@"dtEventStart: %@", dtEventStart);
NSLog(@"dtEventEnd: %@", dtEventEnd);
但是,输出如下所示:
dtEventStart: 2013-01-07 00:30:00 +0000
dtEventEnd: 2013-01-07 12:45:00 +0000
输出时间和日期与用于转换的字符串不同。我也尝试将 EST 用于 timeZone,但会产生不同的错误结果,如下所示:
dtEventStart: 2013-01-07 05:30:00 +0000
dtEventEnd: 2013-01-07 17:45:00 +0000
我知道我错过了一些东西,但我不知道是什么。任何帮助是极大的赞赏。
谢谢
更新:
这是
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent * eventForCalendar = [EKEvent eventWithEventStore:eventStore];
eventForCalendar.title = event.title;
NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];
NSTimeZone *tz = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
[dateFormat setDateFormat:@"M/d/yyyy HH:mm:ss a"];
[dateFormat setTimeZone:tz];
NSDate * dtEventStart = [dateFormat dateFromString:@"1/7/2013 6:30:00 AM"];
NSDate * dtEventEnd = [dateFormat dateFromString:@"1/7/2013 8:45:00 PM"];
NSLog(@"dtEventStart: %@", dtEventStart);
NSLog(@"dtEventEnd: %@", dtEventEnd);
eventForCalendar.startDate = dtEventStart;
eventForCalendar.endDate = dtEventEnd;
[eventForCalendar setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:eventForCalendar span:EKSpanThisEvent error:&err];