2013-05-19 55 views
1

我如何計算今天的小時分鐘和秒鐘爲零的NSTimeInterval?NSTime今天與零時間間隔(午夜)

我知道今天的NSTimeInterval那就是:

NSTimeInterval today = [[NSDate date] timeIntervalSince1970]; 

,但我怎麼可以重設時間?

+1

相對於什麼? – Wain

+0

什麼?...我有今天的nstimeinterval,但我想今天設置它的時間00:00:00 ... – Piero

回答

1
NSDate *currentDate = [NSDate date]; 
NSDateComponents *currentDateComponents = [calendar components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:currentDate]; 
NSDateComponents *currentDateToMidnight = [[NSDateComponents alloc] init]; 
[currentDateToMidnight setHour:-[currentDateComponents hour]]; 
[currentDateToMidnight setMinute:-[currentDateComponents minute]]; 
[currentDateToMidnight setSecond:-[currentDateComponents second]]; 
NSDate *midnight = [calendar dateByAddingComponents:currentDateToMidnight toDate:currentDate options:0]; 
NSTimeInterval todayTimeInterval = [midnight timeIntervalSince1970]; 
+0

這有點矯枉過正,不是嗎?只需將'currentDateComponents'的小時,分​​鍾和秒設置爲0,並詢問日曆將會是什麼'NSDate'。 – JustSid

0

您需要使用NSDateComponents只得到年,月和今天的日子,那麼你就可以創建他們的日期,這將是在午夜。

0

一旦你的nowNSTimeInterval調用以下功能:

inline NSTimeInterval trimTimeInterval(NSTimeInterval interval) 
{ 
    static NSTimeInterval const day = 3600 * 24; 
    return day * floor(interval/day); 
} 

首先我們計算interval的整數天量再拿到相同的值回來的時間元素除外。

但請注意,這段代碼不會考慮時區。所以你可能會在5月23日結束,而不是5月24日,格林威治標準時間+ N> 0。