Jacksonkr
Jacksonkr

Reputation: 32207

ios get 12AM for today

NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setLocale:[NSLocale currentLocale]];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"US/Central"]];

NSDateComponents *nowComponents = [calendar components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];

[nowComponents setHour:hour];
[nowComponents setMinute:0];
[nowComponents setSecond:0];

NSLog(@"%@", [calendar dateFromComponents:nowComponents]);

logs 2012-01-01 06:00:00 +0000. The time is correct based on the timezone setting, but today is July 20th... What am I doing wrong?

Upvotes: 1

Views: 1099

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

You need to extract the year, month, and day components, and construct a new NSDate, like this:

NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setLocale:[NSLocale currentLocale]];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"US/Central"]];

NSDateComponents *nowComponents = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
today = [calendar dateFromComponents:nowComponents];

You do not need to get the time components and then set them back to zero: you can keep them at their defaults by not asking to extract them in the first place.

Upvotes: 1

Related Questions