1

This question follows on from a previous question...

How do I create the current date (or any date) as an NSDate without hours, minutes and seconds?

I would use this code as follows...

NSDate *todaysDate = [General makeAbsoluteNSDate:[NSDate date]];

My problem is that I have users in different countries and UTC isn't their timezone and the date produced by this function at certain times of the day won't be correct.

How do I get the current time zone to correct my function ? Or should I be using a different approach ?

Heres the function I've been using...

+ (NSDate *)makeAbsoluteNSDate:(NSDate*)datSource {

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:
      NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit | 
                  NSMonthCalendarUnit | NSDayCalendarUnit
                  fromDate:datSource];
[dateComponents setHour:0];
[dateComponents setMinute:0];
[dateComponents setSecond:0];

NSDate *midnightUTC = [calendar dateFromComponents:dateComponents];
[calendar release];

return midnightUTC;
}
Community
  • 1
  • 1
Jules
  • 7,568
  • 14
  • 102
  • 186

1 Answers1

0

You get the timezone object from this call:

[NSTimeZone localTimeZone]

And you can use the secondsFromGMT method to figure out the difference and create a date with the timezone.

You can even build a Category for NSDate that includes a method to transform a date into the current timezone date, which would be even simpler.

Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158
  • Thanks, wouldn't I just need to use localTimeZone in this scenario ? – Jules Aug 13 '11 at 11:32
  • Well, you have to get a date and transform it to something else, I'd say just calculating the difference between the two of them is surely simpler than creating a NSCalendar, but that's just taste, as long as it solves your problem that's good enough for me :) – Maurício Linhares Aug 13 '11 at 11:38