Increase NSDate +1 day method Objective-C?

前端 未结 2 1915
无人及你
无人及你 2020-12-09 19:47

This is my method I use for increasing by one day in my navigationBar, and setting the name of the day as a title. I know it\'s wrong because I set \"today\" variable every

相关标签:
2条回答
  • 2020-12-09 20:12

    As from iOS 8 NSGregorianCalendar is depricated, the updated answer will be,

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.day = 1;
    NSDate *newDate = [calendar dateByAddingComponents:components toDate:today options:0];
    

    Swift Code:

    var today:NSDate = NSDate()
    let calender:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    var components:NSDateComponents = NSDateComponents()
    components.setValue(1, forComponent: NSCalendarUnit.CalendarUnitDay)
    var newDate:NSDate! = calender.dateByAddingComponents(components, toDate:today, options: NSCalendarOptions(0))
    
    0 讨论(0)
  • 2020-12-09 20:13

    Store the date your are showing in a property (ivar, ...) of your view controller. That way you can retrieve the current setting when you go to the next day.

    If you want to reliably add dates, use NSCalendar and NSDateComponents to get a "1 day" unit, and add that to the current date.

    NSCalendar*       calendar = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar] autorelease];
    NSDateComponents* components = [[[NSDateComponents alloc] init] autorelease];
    components.day = 1;
    NSDate* newDate = [calendar dateByAddingComponents: components toDate: self.date options: 0];
    
    0 讨论(0)
提交回复
热议问题