Levente Kürti
Levente Kürti

Reputation: 1015

UIDatePicker & NSDateFormatter returning incorrect date

I have allready tryed solutions from a few posts, but no luck. The problem is that i'm facing is probably whit time zones. Both on device and simulator UIDatePicker and NSDateFormatter are returning incorrect dates, adding or substracting the difference from GMT 0, from the selected date (according to the current time zone set on the device or mac).

I have allready tried setting locale and time zone but nothing worked. Any idea is wellcomed! Thanks.

(Haven't posted any code sample because both are initialized without setting any properties right now.)

UPDATE 1:

Here is the code snippet:

 datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, frame.size.height - 216.0, frame.size.width, 216.0)];

    [self addSubview:datePicker];

    ....


    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    [formatter setDateFormat:@"EEE, MMM d, y h:mma"];

    NSString *dateString = [formatter stringFromDate:datePicker.date];
    [formatter release];

Upvotes: 0

Views: 3519

Answers (2)

Levente Kürti
Levente Kürti

Reputation: 1015

Found the solution, the time zone difference should be added in the following way.

- (NSDate *)dateToGMT:(NSDate *)sourceDate {
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:destinationGMTOffset sinceDate:sourceDate] autorelease];
    return destinationDate;
}

Upvotes: 14

William Jockusch
William Jockusch

Reputation: 27295

You said you set the time zone, but you didn't say where. You need to set the timeZone properties of your UIDatePicker and your NSDateFormatter.

Upvotes: 0

Related Questions