I'm trying to put a time value on a time picker, the problem is that the time gets messed up because of time zone issue. Here's the code snippet I use:
int targetmillisondsFromMidnight = [self.schedule.targetHour intValue]; // 59580000
NSDate* todayMidnight = [NSCalendar.currentCalendar startOfDayForDate:[NSDate new]]; //2019-12-23 00:00:00 UTC
NSTimeZone* timezone = [NSTimeZone defaultTimeZone];
NSInteger seconds = [timezone secondsFromGMT];
todayMidnight = [todayMidnight dateByAddingTimeInterval:seconds];
NSDate* scheduleDate = [NSDate dateWithTimeInterval:targetmillisondsFromMidnight/1000 sinceDate:todayMidnight]; //2019-12-23 16:33:00 UTC
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone defaultTimeZone]];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:scheduleDate];
[self.datePicker setTimeZone:[NSTimeZone defaultTimeZone]];
[self.datePicker setDate:[calendar dateFromComponents:components] animated:YES];
When I do po [components hour]
instead of getting 16 as in the scheduleDate
I get 18.
How can I fix this?
I tried to change the time zones to localTimeZone
and timeZoneWithAbbreviation:@"GMT"
but nothing seems to work.