views:

333

answers:

3

I want to take the next day by giving the current date The code i used as follows

+(NSDate *)getForDays:(int)days fromDate:(NSDate *) date {
    NSTimeInterval secondsPerDay = 24 * 60 * 60 * days;
        return [date addTimeInterval:secondsPerDay];
}

this works fine but when the daylight saving enabled this leads to errors. How can I make this work when daylight saving is enabled.

A: 

I've no idea what language or system you're using here, but my advice would be to perform all of your calculations using time as UTC and only use local time when you come to display it.

Most operating systems and languages will factor in timzone and daylight saving on the conversion of UTC to local time.

ChrisBD
A: 

Use NSCalendar to perform calculations like this. Not only is it more likely to work, but your code will be clearer.

Peter Hosey
+1  A: 

As you have found, what you have now is pretty error-prone. Not only can it trip up over a daylight savings change, but also what if your user has a non-gregarian calendar? Then, days are not 24 hours long.

Instead, use NSCalendar and NSDateComponents which were exactly designed for this:

  1. Grab the appropriate NSCalendar object for the date you are working with. Sounds to me like you probably just want the default calendar.
  2. Use the NSCalendar object to break your NSDate up into a NSDateComponents object.
  3. Increment the NSDateComponents object's day by one.
  4. Use the calendar to generate a new date from the mutated NSDateComponents object.
Mike Abdullah