Question

I am using following piece of code to get next week date from a given date at 12:00am:

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit |NSHourCalendarUnit fromDate:now];
[components setHour:0];
NSDate *todayDate = [calendar dateFromComponents:components];


int daysToAdd = 7;
NSDate *tomorrowDate = [todayDate dateByAddingTimeInterval:60*60*24*daysToAdd];


NSString *stringDate = [NSString stringWithFormat:@"%@",tomorrowDate];
todoItemDueDateText.text = stringDate;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"EEEE, dd MMMM YYYY"];
NSString *fechasimulada = [dateFormatter stringFromDate:tomorrowDate];
dateFieldSimulatedText.text = fechasimulada;

If I log the result date, it is working fine.

Now, a similar piece of code to get next month date from a given date at 12:00am:

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:0];
NSDate *todayDate = [calendar dateFromComponents:components];


//NSDate *today = [NSDate date];
NSDateComponents* dateComponents = [[NSDateComponents alloc]init];
[dateComponents setMonth:1];
//NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* tomorrowDate = [calendar dateByAddingComponents:dateComponents toDate:todayDate options:0];


NSString *stringDate = [NSString stringWithFormat:@"%@",tomorrowDate];
todoItemDueDateText.text = stringDate;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"EEEE, dd MMMM YYYY"];
NSString *fechasimulada = [dateFormatter stringFromDate:tomorrowDate];

I don't know why, but the second piece of code gives the expected date but -1 hour.

UPDATE:

I will show you the dates:

Source date (today at 12:00am)+7 h

enter image description here

Next week date from previous given date:

enter image description here

Next month date from previous given date:

enter image description here

Was it helpful?

Solution

NSDate takes Daylight Savings into account. If you cross a DST day, you'll experience this issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top