是否可以从基于NSString
的日期解析出日期组件?例如,如果我有NSDateFormatter
yyyy-MM-dd HH:mm:ss.SSS ZZZ
,如何直接从此字符串中获取NSDateComponents
对象?
具体来说,我希望保留时区,并将此NSDateComponents
对象与使用yyyy-MM-dd
格式创建的对象区分开来。
答案 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];