2

我正在尝试将字符串转换为 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];
4

2 回答 2

0

Try following code:-

NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

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);

You will get following output with 24 hours format:-

dtEventStart: 2013-01-07 06:30:00 +0000
dtEventEnd: 2013-01-07 20:45:00 +0000
于 2013-01-08T09:01:26.110 回答
0

对于解析,文档建议首先将日期格式化程序的语言环境设置为 en_US_POSIX:

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW7

此外,这个关于日期格式化程序的问答:

http://developer.apple.com/library/ios/#qa/qa1480/_index.html

我正在使用 NSDateFormatter 来解析 Internet 样式的日期,但这对于某些地区的某些用户来说失败了。我已经设置了一个特定的日期格式字符串;这不应该强制 NSDateFormatter 独立于用户的区域设置工作吗?

不可以。虽然设置日期格式字符串似乎适用于大多数用户,但这并不是解决此问题的正确方法。格式字符串在许多地方以意想不到的方式表现。例如:

于 2013-01-07T23:57:33.647 回答