Need a solution to convert and store date/time in correct local time compared to device timezone
Ok, I am not sure how to ask this question so that it can be understood...
I need to store some schedules on a server (Ruby on Rails) from a iPhone. On the iPhone device the time is relative to the device timezone settings, but on the server I need to store the data in the servers local timezone correctly so that the scheduled event will be fired at the correct time.
开发者_StackOverflow中文版My idea was this: - Convert iPhone time to UTC timezone time, and send to server - On server, read all stored timestamps as UTC timezone - For data received from server, convert from UTC timezone time to local timezone time
Here is my code to convert to UTC time:
// First the NSDateformatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
// Now the conversion from local timezone to UTC
NSTimeZone *srcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSTimeZone *destTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [srcTimeZone secondsFromGMTForDate:srcDate];
NSInteger destinationGMTOffset = [destTimeZone secondsFromGMTForDate:srcDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate *destDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:srcDate] autorelease];
The problem is, that if I try and change timezone on my iPhone in between two posts to the server, there is a time difference, so something is wrong.
So my question(s) is: 1) Is this a good approach? 2) What is wrong with my code?
Thank you Søren
You shouldn't be fiddling with time zones except for the UI.
Instead, you should save all you times using timeIntervalSinceReferenceDate
which is the NSDate primitive method that returns the number of elapsed seconds, to the microsecond, that have elapsed since 1 January 2001, GMT and the current GMT date and time. Save that number to the server and then you can convert it to dates with timezones as needed for display.
Data and time programming is deceptively complex. Keep everything as simple and fixed as possible in the core logic.
精彩评论