我正在使用以下字符串中的NSDateComponents
建立日期:
"2014-05-17 02:39:00 PM +0000"
当我设置所有组件并返回我正在获取的NSDate时(参见下面的方法):
"2014-05-17 02:39:00 AM +0000"
我的问题是,有没有办法将AM / PM指定为NSDateComponent
,或者如果源日期是PM,我是否只需要将12添加到我的小时?
- (NSDate *)dateFromYear:(int)year month:(int)month day:(int)day hour:(int)hour minute:(int)minute {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[components setYear:year];
[components setMonth:month];
[components setDay:day];
[components setHour:hour];
[components setMinute:minute];
NSCalendar *calendar = [NSCalendar currentCalendar];
return [calendar dateFromComponents:components];
}
答案 0 :(得分:2)
显然,NSDateComponents似乎没有指明这一点。 Apple自己的文档说明了这一点:
重要说明:NSDateComponents对象本身没有意义;您 需要知道它被解释的日历,你需要 知道这些值是否是单位的绝对值,或者 数量单位。
除了12小时的逻辑外,您还可以使用使用AM / PM的NSDate类dateWithNaturalLanguageString并以某种方式使用它。