2011-06-05 55 views
5

我有最簡單的任務,我無法弄清楚如何正確執行。通過下面的代碼片段,我可以找出一個月的開始。計算月末或其最後一秒

NSCalendar *cal = [NSCalendar currentCalendar]; 
NSDate *beginning = nil; 
[cal rangeOfUnit:NSMonthCalendarUnit startDate:&beginning interval:NULL forDate:self]; 
return beginning; 

現在我想確定同一個月的結束(在23:59:59的最後一秒會適合我的目的)。我的第一個想法是在下個月的第一天開始,並減去第二天。但我無法將NSDateComponent實例中的日期分解爲[dateComponents setMonth:[dateComponents month] + 1],因爲在12月的情況下,該方法不會接受12 + 1 = 13來到1月份,對吧?

那我怎麼會到一個月的最後一秒呢?

+0

但你確定最後一秒是本月底嗎?怎麼樣 - 但是最後_millisecond_? – xtofl 2011-06-05 20:22:41

+0

這也完全沒問題。有任何想法嗎? – epologee 2011-06-05 20:23:57

回答

3

這樣做是爲了獲得下個月開始:

NSDateComponents *comps = [[NSDateComponents alloc] init]; 
[comps setMonth:1]; 
NSDate *beginningOfNextMonth = [cal dateByAddingComponents:comps toDate:beginning options:0]; 
[comps release]; 
+0

這甚至更好。我正在慢慢放寬日期組件的許多用途,謝謝! – epologee 2011-06-05 20:44:21

+1

要真正獲得最後一秒,請在上面添加一個'[comps setSecond:-1];'。 – spacehunt 2011-06-05 20:45:36

+0

明白了,像魅力一樣工作。再次感謝! – epologee 2011-06-05 20:48:32

0

本月的最後一秒......大部分時間,歸結爲下一個月的第一秒,然後減去一秒鐘。

但你問的是正確的問題?最後一秒的含義是什麼?我的猜測是你想要表示一個時間間隔,從N月的第一秒開始(包括)開始,並且在N + 1月的第一秒之前結束。

+0

好的,改述一下:我如何到下個月的開始? – epologee 2011-06-05 20:30:19

+2

使用NSCalendar的'dateByAddingComponents:toDate:options:'來進行日期計算。 – spacehunt 2011-06-05 20:38:48

3

好吧,我想我有它。我使用rangeOfUnit:inUnit:forDate:方法確定當前月份的天數,並將相應的NSTimeInterval添加到月份的開始日期。

- (NSDate *)firstSecondOfTheMonth { 
    NSCalendar *cal = [NSCalendar currentCalendar]; 
    NSDate *beginning = nil; 
    if ([cal rangeOfUnit:NSMonthCalendarUnit startDate:&beginning interval:NULL forDate:self]) 
     return beginning; 
    return nil; 
} 

- (NSDate *)lastSecondOfTheMonth { 
    NSDate *date = [self firstSecondOfTheMonth]; 
    NSCalendar *cal = [NSCalendar currentCalendar]; 
    NSRange month = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date]; 
    return [date dateByAddingTimeInterval:month.length * 24 * 60 * 60 - 1]; 
} 

注:雖然此代碼的工作,因爲我想要它工作,the answer that @spacehunt了更清晰通信的目的。