dsr
dsr

Reputation: 21

How to get tomorrow's date at 6am using objective c?

Hi Here is my problem. Given today's date, I have to get tomorrow's date but the time should be set to 6am. I use NSDate and NSDateComponents. But it always adds 5 hours extra to 6am and NSDate returned is always at 11am. What am I doing wrong here? Here is my code:

//1. Get today's date
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone defaultTimeZone]];
NSLog(@"1 Today %@", today);

//2. Get tomorrow's date
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: today options:0];
NSLog(@"2 nextDate %@", nextDate);

//3. Get the data components for tomorrow's date to set the time
NSDateComponents *nextDateComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:nextDate];
NSInteger theDay = [nextDateComponents day];
NSInteger theMonth = [nextDateComponents month];
NSInteger theYear = [nextDateComponents year];

//4. Build tomorrow's date with time at 6am
NSDateComponents *tomorrowComponents = [[NSDateComponents alloc] init];
[tomorrowComponents setDay:theDay];
[tomorrowComponents setMonth:theMonth];
[tomorrowComponents setYear:theYear];
[tomorrowComponents setHour:6];
NSDate *tomorrow = [gregorian dateFromComponents:tomorrowComponents];
NSLog(@"3 Tomorrow %@", tomorrow);
[gregorian release];

Upvotes: 2

Views: 2796

Answers (3)

Joel
Joel

Reputation: 16124

You need to format the date you are logging to convert to a string using right locale.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
NSLocale *enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
[dateFormatter setLocale:enUSPOSIXLocale];
dateFormatter.dateFormat = @"MM-dd-yyyy h:mm a";
NSLog(@"3 Tomorrow %@", [dateFormatter stringFromDate:tomorrow]);
[dateFormatter release];

Upvotes: 1

Marc
Marc

Reputation: 11

It's a timezone issue. You're setting the time to 6am locally, but returning GMT.

Upvotes: 0

Marcelo Alves
Marcelo Alves

Reputation: 1846

Looks like you forgot to copy the timezone.

Upvotes: 0

Related Questions