Reputation: 149
I have been browsing the apple docs and stackoverflow for a while now, but I wasn't be able to find a correct answer for my problem. I'll try to explain. In my app a user is able to create measurements on a specific time. The date and time of the measurement is important.
In my NSDate+Helper category I created the following helper methods:
- (NSDate *)dateByMovingToBeginningOfDay
{
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:self];
[parts setHour:0];
[parts setMinute:0];
[parts setSecond:0];
return [[NSCalendar currentCalendar] dateFromComponents:parts];
}
- (NSDate *)dateByMovingToEndOfDay {
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:self];
[parts setHour:23];
[parts setMinute:59];
[parts setSecond:59];
return [[NSCalendar currentCalendar] dateFromComponents:parts];
}
This methods helps me to get a range of measurements from a complete day:
NSDate *start = [[NSDate date] dateByMovingToBeginningOfDay];
NSDate *end = [[NSDate date] dateByMovingToEndOfDay];
NSMutableSet *measurementsSet = [trainingsPlan measurementsWithType:@"used" fromDate:start andToDate:end];
There is where my problem comes in. Let's say I add a measurement on my simulator at 2012-03-14 0:42:59 (GMT+1)
-because that's the time displayed on my simulator- and save it in core data.
[NSDate date]
at that moment is 2012-03-13 23:42:59
so NSDate *start = [[NSDate date] dateByMovingToBeginningOfDay];
gives me the start date of the day before. This is a problem.
My question, what is the best approach that it will work for users in all different timezones?
Upvotes: 2
Views: 1206
Reputation: 25740
If you want to use the same data across multiple time zones then your only option is to use the same timezone in your app, no matter what time the iPad says. Generally you use UTC for this purpose (and is the default time zone that times are created and saved in).
If you just want it to match the local timezone, then you need to change your routines like this:
- (NSDate *)dateByMovingToBeginningOfDay
{
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents* parts = [calendar components:flags fromDate:self];
[parts setHour:0];
[parts setMinute:0];
[parts setSecond:0];
return [calendar dateFromComponents:parts];
}
Update the second routine in the same way.
Upvotes: 3