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

后端 未结 2 864
名媛妹妹
名媛妹妹 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: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.

提交回复
热议问题