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

后端 未结 2 841
名媛妹妹
名媛妹妹 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];
    
    0 讨论(0)
  • 2021-01-03 16:55

    NSDate is a bit of a misnomer. It is a not a simple date, it is a date a time, with subsecond level precision. The earlierDate: method is a comparison function that returns which ever of the two dates is earlier, it does not create an earlier date. If all you care about is a date that is before your current one you can do:

    NSDate *earlierDate = [date addTimeInterval:-1.0];
    

    Which will return a date 1 second before date. Likewise you can do

    NSDate *laterDate = [date addTimeInterval:1.0];
    

    for a date 1 second in the future.

    If you want a day earlier you can add a days worth of seconds. Of course that is approximate unless you deal with all the gregorian calendar issues, but if you just want a quick approximation:

    NSDate *earlierDate = [date addTimeInterval:(-1.0*24*60*60)];
    

    That doesn't work with leap seconds, etc, but for most uses it is probably fine.

    0 讨论(0)
提交回复
热议问题