I’ve been struggling with my function to return todays date, at as close to zero seconds, minutes and hours as possible. So I’m able to re-use the same date with various transactions.
However, I’ve now discovered that my function returns yesterdays date?
+ (NSDate *)makeAbsoluteNSDate:(NSDate*)datSource {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:
NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit |
NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:datSource];
[dateComponents setHour:0];
[dateComponents setMinute:0];
[dateComponents setSecond:0];
NSDate *today = [calendar dateFromComponents:dateComponents];
[calendar release];
return today;
}
If you’re trying to get today’s or yesterday’s midnight in your time zone, you should get
NSDatethat points to adequate time in GMT. In my case -2 hours as my timezone is +0200, so for midnight of 2011-08-26 I’ll get 2011-08-25 22:00.You have to make sure that you’re setting the right timezone for the
NSCalendar, which is[NSTimeZone systemTimeZone].My routine for getting the midnight in my time zone is:
So, after a long discussion in comments, here’s a midday function: