2011-08-13 28 views
1

從以前的問題,這個問題在如下...如何在當前時區創建沒有小時的日期?

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

如下我會使用此代碼...

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

我的問題是,我可以在不同國家的用戶和UTC不是它們的時區,並且該功能在一天的特定時間生成的日期不正確。

如何獲取當前時區以更正我的功能? 或者我應該使用不同的方法?

繼承人的功能,我使用了...

+ (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; 
} 

回答

0

你從該呼叫的時區對象:

[NSTimeZone localTimeZone] 

而且你可以使用secondsFromGMT方法找出區別並創建與時區的日期。

你甚至可以爲NSDate構建一個類別,該類別包含一個將日期轉換爲當前時區日期的方法,這將更加簡單。

+0

謝謝,我不是隻需要在這種情況下使用localTimeZone? – Jules

+0

好吧,你必須得到一個日期並將其轉換爲其他東西,我只是說計算它們兩者之間的差別肯定比創建一個NSCalendar簡單,但這只是味道,只要它解決了你的問題,那就是對我來說足夠好:) –

相關問題