将基于日期的NSString转换为NSDateComponents

时间:2016-03-14 23:25:11

标签: objective-c cocoa nsdate nsdateformatter nsdatecomponents

是否可以从基于NSString的日期解析出日期组件?例如,如果我有NSDateFormatter yyyy-MM-dd HH:mm:ss.SSS ZZZ,如何直接从此字符串中获取NSDateComponents对象?

具体来说,我希望保留时区,并将此NSDateComponents对象与使用yyyy-MM-dd格式创建的对象区分开来。

1 个答案:

答案 0 :(得分:0)

不是那么直接,但只需几步:

NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS ZZZ"];

NSString *dateString = @"2016-03-15 12:00:00.000 +0800";
NSDate *date = [formatter dateFromString:dateString];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitTimeZone fromDate:date];

NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSTimeZone *timeZone = [components timeZone];