views:

45

answers:

2

Hello, 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];
A: 

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.

William Jockusch
I have updated the initial post with the code. I tried to set the timeZone properties to: defaultTimeZone, localTimeZone, even specifying GMT +3, but they still returned incorrect date.
Levi Kurti
A: 

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;
}
Levi Kurti