I want to get a quarter value in NSDateComponents class

房东的猫 提交于 2019-11-26 18:34:38

问题


I want to get a quarter value from specified date. (*date variable)

So. I have made following code and run. but, quarter value is zero.

Why quarter value is zero? where's problem?

Please advice from advanced man.

NSDateComponents *comp1 = [[NSDateComponents alloc] init];
[comp1 setYear:2012];
[comp1 setMonth:6];
[comp1 setDay:1];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDate *date = [gregorian dateFromComponents:comp1];  <== want to get a quarter value.

unsigned int unitFlags = NSYearCalendarUnit | NSQuarterCalendarUnit | NSMonthCalendarUnit | NSWeekOfYearCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *comp2 = [gregorian components:unitFlags fromDate:date];

NSLog(@"year :       %5d",[comp2 year]);
NSLog(@"quarter :    %5d",[comp2 quarter]);
NSLog(@"month :      %5d",[comp2 month]);
NSLog(@"weekofYear : %5d",[comp2 weekOfYear]);
NSLog(@"day :        %5d",[comp2 day]);

Result:

2012-07-24 03:44:14.776 dateTest[1228:1307] year :        2012
2012-07-24 03:44:14.776 dateTest[1228:1307] quarter :        0
2012-07-24 03:44:14.777 dateTest[1228:1307] month :          6
2012-07-24 03:44:14.777 dateTest[1228:1307] weekofYear :    22
2012-07-24 03:44:14.778 dateTest[1228:1307] day :            1

回答1:


It seems that there is an issue with the NSQuarterCalendarUnit being ignored (haven't verified, but did see a bug reported). Anyway, it is simple enough to get around... Just use the NSDateFormatter class.

// After your NSDate *date, add...
NSDateFormatter *quarterOnly = [[NSDateFormatter alloc]init];
[quarterOnly setDateFormat:@"Q"];

int quarter = [[quarterOnly stringFromDate:date] intValue];

// Then change the quarter NSLog too
NSLog(@"quarter :    %5d", quarter);

Should work fine...




回答2:


Dec 16 2014

How about simply:

([comp2 month]-1)/3+1;



来源:https://stackoverflow.com/questions/11618784/i-want-to-get-a-quarter-value-in-nsdatecomponents-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!