1

I have a UIDatePicker and a button. When I press the button I want to display in the log the message "Setting a reminder for x" where x is the time displayed by the date picker.

Everytime I press the button, the time logged is precisely 3 hours behind the time displayed by the picker (the time displayed by the picker is my current time). I suspect it has something to do with the time zone. I live in GMT +2 time zone (I guess it's +3 since we are in daylight saving time).

Do you have any idea how I could make the time logged to be the same as the time displayed?

Below is the method that gets executed when I press the button. Thanks.

- (IBAction)addReminder:(id)sender {
    [self.datePicker setTimeZone:[NSTimeZone systemTimeZone]];
    NSLog(@"Setting a reminder for %@", self.datePicker.date);
}
Alex Craciun
  • 473
  • 1
  • 3
  • 13
  • 1
    possible duplicate of [How to convert UTC date string to local time (systemTimeZone)](http://stackoverflow.com/questions/11677520/how-to-convert-utc-date-string-to-local-time-systemtimezone) – James Zaghini Sep 09 '15 at 12:52
  • This also could be an issue with the simulator timezone as opposed to your timezone. Check the ios simulator settings for more info – Devster101 Sep 09 '15 at 12:53
  • The time on the simulator is the same as the real time. I tried to change the region on the iOS simulator and the result is exactly the same. – Alex Craciun Sep 09 '15 at 13:03

2 Answers2

0

NSDate is simple representation of some moment in time, it knows nothing about your local time. When you log it (actually, when description) message is sent, it uses GMT to display itself.

UIDatePicker uses your timezone by default (see https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDatePicker_Class/#//apple_ref/occ/instp/UIDatePicker/timeZone).

So, here is how it works:

  • You choose some time in DatePicker, but time is meaningless unless you specify timezone.
  • DatePicker uses your local (GMT+2) timezone and creates NSDate for it.
  • You display NSDate and since it knows nothing about timezone, it simply displays itself as GMT.

To display your date, your should use NSDateFormatter. It has Timezone property: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/#//apple_ref/occ/instp/NSDateFormatter/timeZone

You can also use NSCalendar and its components.

You should read this guide: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html since dates, formatters and calendars are not very clear in Cocoa unless you understand its concepts.

user996142
  • 2,753
  • 3
  • 29
  • 48
0

Try this...

NSDate *now = [[NSDate alloc] init];
[self.datePicker setDate:now];
[self.picker setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:2*60*60]]; // GMT+2 Your timeZone
NSLog(@"Setting a reminder for %@", self.datePicker.date);
Bhadresh
  • 417
  • 5
  • 6