0

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.

Keselme
  • 3,779
  • 7
  • 36
  • 68

1 Answers1

0

It looks like you do superfluous conversion

Let's consider the following code

NSDate *date = [NSDate new]; // << in UTC always

NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone defaultTimeZone]]; // << in local 

NSDateComponents *components = [calendar components:
   (NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date]; // << converted to local

debug output:

  (lldb) po date
  2019-12-24 09:53:12 +0000

  (lldb) po components
  <NSDateComponents: 0x600003c78710> {
    Hour: 10
    Minute: 53
Asperi
  • 228,894
  • 20
  • 464
  • 690