How do I get the next and earlier date of the current date in iPhone sdk

后端 未结 2 855
名媛妹妹
名媛妹妹 2021-01-03 15:50

I have a date object,

NSDate *date = [NSDate date];

Now I want a date earlier of this date and next of it. What function should I use.

Earlier and La

2条回答
  •  借酒劲吻你
    2021-01-03 16:46

    You need to use NSCalendar and NSDateComponents to do this calculation reliably.

    Here's an example I have to hand to compute an NSDate for noon today. I'm sure you can work out how to get the result you want from this and the documentation.

    NSDate *today = [NSDate date];
    
    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents* todayComponents = [gregorian components:unitFlags fromDate:today];
    
    todayComponents.hour = 12;
    
    NSDate* noonToday = [gregorian dateFromComponents:todayComponents];
    

提交回复
热议问题