2012-06-13 105 views
0

如何計算只有星期數和星期幾的日期?計算一週中的日期數

E.g. 2012年的第24周,星期一開始。

+0

這可能會給你一個指針http://stackoverflow.com/questions/2466022/how-to-find-weekday-from-todays-date-in-iphone-sdk – geminiCoder

回答

1

很方便,NSCalendar會爲你做所有的數學。首先,設置使用NSDateComponents參數:

NSDateComponents *comps = [[NSDateComponents alloc] init]; 
[comps setWeek:24]; 
[comps setWeekday:3]; //map weekday names to numbers (e.g., Sunday is 1) 
[comps setYear:2012]; 

然後創建與最新組件公曆:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

而且抓住你的NSDate:

NSDate *date = [gregorian dateFromComponents:comps]; 
+0

它的工作原理!謝謝! :) – Oleg

+1

正如我上面寫的你的解決方案工作正常!但現在我遇到了另一個問題 - 它檢測到前一天的日期:2012-06-11 22:00:00 +0000而不是2012-06-12 00:00:00。我認爲這是與時區有關的東西。我所有的日期應該在GMT + 2時區。你能幫忙嗎? – Oleg

+1

好問題。處理時區是棘手的,取決於你想要做什麼,但如果你不關心時間,只想要日期,我認爲一個簡單和安全的解決方法是在GMT(+0000)中工作。爲此,請在獲取日期前添加以下行:'[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@「GMT」]];'。這適用於我,但其他人可能會有更好的答案。 –

0
NSDate *now = [NSDate date]; 
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSDateComponents *comp = [gregorian components:NSYearCalendarUnit fromDate:now]; 
    [comp setWeek:24]; 
    [comp setDay:1]; 
    NSDate *resultDate = [gregorian dateFromComponents:comp]; 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setDateFormat:@"MMM d, yyyy"]; 


    NSString *myDateString = [formatter stringFromDate:resultDate]; 

    [gregorian release]; // Clean up allocated objects by releasing them 
    [formatter release]; 

    NSString * date = [NSString stringWithFormat:@"Week of %@", myDateString];