我需要从当前日期开始上周和月。
所以我找到了可以重新计算当前日期添加间隔的解决方案
- dateByAddingTimeInterval
这就是它的代名词:
[[NSDate date] dateByAddingTimeInterval: -604800.0]
(上周获得)
[[NSDate date] dateByAddingTimeInterval: -2629743.83]
(上个月获得)
正如我认为一周这个方法运行良好没有任何问题,因为每周有七天,间隔不会改变。但是对于一个月我们有一个问题,因为每个月都有不同的天数。
答案 0 :(得分:35)
使用NSDateComponents
可以轻松准确
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
comps.month = -1;
comps.day = -1;
NSDate *date = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
NSDateComponents *components = [calendar components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date]; // Get necessary date components
NSLog(@"Previous month: %d",[components month]);
NSLog(@"Previous day : %d",[components day]);
答案 1 :(得分:9)
请勿使用903484和-23484更改日期
这样做:
NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components=[[NSDateComponents alloc] init];
components.month=1;//next month
components.month=-1;//previous month
//similarly +1 and -1 will give you week and month day etc
components.week=1;
components.day=1;
NSDate *myMonth=[gregorian dateByAddingComponents:components toDate:today options:0];
NSDateComponents *components = [calendar components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
NSInteger yourRequiredValue=[components day]; //day, month, week etc