Ronald Hofmann
Ronald Hofmann

Reputation: 1430

UIDatepicker returns wrong value

my UIDatepicker returns a wrong value and I don´t understand why. See picture.
It shows 0 hours and 1 min but the label shows -1 hour.
I don´t find an time zone to set up. I expected that my app uses the time zone of the machine it´s on.

My action to fill the label:

- (IBAction)datePickerDateChanged:(id)sender {
   [_timerOutput setText:[NSString stringWithFormat:@"%@", [_timePicker date]]];
}

I´m on a German system and I set the UIDatepicker to German but it still shows hours and mins.

Any idea what I´m doing wrong?

Ronald

enter image description here

Upvotes: 1

Views: 693

Answers (1)

vikingosegundo
vikingosegundo

Reputation: 52237

This is the date and time in GMT wintertime (== UTC). use a NSDateFormatter to adjust it, it should use the default timezone by default. you also can set another.

try

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSString *myDateString = [dateFormatter stringFromDate: [_timePicker date]];
NSLog(@"%@", myDateString);

Some theory:

A NSDate object does not represent what we call a date in every-days sense, like a day or a time of range, or what ever. It represents a single point in time. with sub-millisecond precision. And it does so by counting time intervals. From the beginning of a certain era. and by definition it is keeping UTC timezone as reference.
The internal counter will always be counting in UTC-context, it is your responsibility to display it correctly. But the NSDateFormatter is of huge help for that.
BTW: That your displayed time is a UTC time formatted one is also shown by +0000, as it has 00 hours and 00 minutes timezone offset from UTC.

Upvotes: 2

Related Questions