Question

I have an array of NSDates which I build from strings using [NSDate dateFromString] In the xml I parsed to get the string there was also a timezone string. As far as I can see in the manual NSDate does not in it self deal with timezones. Do I need to always store this timezone value somewhere and pair it with the belonging NSDate each time I need it?

I also need to figure out that if an event starts in London at 10:00, but I am in Denmark having my iPhone set to danish time my "event started in London" should display at 09:00 o'clock.

Again if an event starts in London at 10:00 o'clock and ends in Denmark at 12:00 o'clock, If I were to compare start time and end time using an iPhone with danish settings I would get that the duration of the event was 02:00 event though 10:00 o'clock in UK and 12:00 o'clock in Denmark is only 1 hour apart.

NSdate works really well for these things in the scope of one timezone, but introducing the timezone part just made everything complicated to me. Is there a way to abstract/hide all these calculations, as I see potential for making a lot of mistakes.

I have been through the NSDateformatter and NSDate guides from Apple, but they are really vague and sports a substantial amount of deprecated code :/

Thanks for any help given.

Was it helpful?

Solution

You should take one standard timezone like UTC/GMT format for all calculation.

OTHER TIPS

According to the NSDate reference, dateWithString: takes an offset to GMT as last component; while it is not a time zone, it is sufficient to perform computation or comparison).

Looking at the NSTimeZone reference, you can use the abbreviationForDate: and the timeZoneWithAbbreviation: to get a NSTimeZone object from a NSDate instance. Once you get the time zone, you have everything you need.

I convert the present date and the date I would like to know if is close, to GMT and then returning the difference. So I changed every thing to deal with differences instead of actual times and dates. A bit like a music score transposed to a different key:)

+ (NSInteger) minutesUntilDate:(NSDate*) date withTimezoneOffset:(NSInteger) GMTOffset     
{

 NSDate *now = [NSDate date];
 NSTimeInterval localTimeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT];

 now = [now addTimeInterval:(localTimeZoneOffset * -1)];

 date = [date addTimeInterval:(GMTOffset * 60 * 60) * −1];

 return ((NSInteger)[now timeIntervalSinceDate:date] / 60 ) * -1;
}

As soon as you have allocated an NSDate, these do not have timezone information any longer. NSDate is "timezone-less" and is always in GMT. You should make sure that NSDate understand your format correctly when allocating it.

Once you have an NSDate you can make normal calculations and ignore the timezones.

You only need to take care of timezones when reading strings into NSDates and when printing them out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top