开发者

How can I create a date with no hours in the current time zone?

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 h开发者_运维知识库ave 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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜