2013-08-29 53 views
3

搜索完SO後,除了this question之外,我找不到解決方案。我正在考慮創建將接受數週的int和今年int這將與月份的名稱返回NSString的方法:將某一年份的周編號轉換爲月份名稱

- (NSString *)getMonthNameFromNumber:(int)weekNumber andYear:(int)year

但我不能找到解決這個問題的方法。如果有人能提供建議,會很高興。

+2

NSDateComponents可能是有用的。 – Larme

+0

使用NSDateFormatter'monthSymbols'而不是'setDateFormat'。 https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDateFormatter/monthSymbols –

回答

4

像這樣的事情會做

​​

注意,這是依賴於設備的偏好設置當前日曆。

如果這不符合您的需要,您可以提供一個NSCalendar實例並使用它來檢索日期而不是使用currentCalendar。通過這樣做,您可以配置諸如哪一天是一週的第一天等等。 NSCalendardocumentation值得一讀。

如果使用自定義日曆是一種常見的情況下,只是改變了實施類似

- (NSString *)monthNameForWeek:(NSUInteger)week inYear:(NSInteger)year { 
    [self monthNameForWeek:week inYear:year calendar:[NSCalendar currentCalendar]]; 
} 

- (NSString *)monthNameForWeek:(NSUInteger)week inYear:(NSInteger)year calendar:(NSCalendar *)calendar { 
    NSDateComponents * dateComponents = [NSDateComponents new]; 
    dateComponents.year = year; 
    dateComponents.weekOfYear = week; 
    dateComponents.weekday = 1; // 1 indicates the first day of the week, which depends on the calendar 
    NSDate * date = [calendar dateFromComponents:dateComponents]; 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setDateFormat:@"MMMM"]; 
    return [formatter stringFromDate:date]; 
} 

到無關的方面說明,你應該避免get的方法名,除非你正在返回間接的價值。

+0

...應該返回一週中第一天下跌的月份的名稱。如果您擔心跨越數月的數週,您可以使用其他日期組件提前6天,並檢查一週中的最後一天。也準備在不同地區給出略微不同的答案 - 週一是世界大部分地區的一週開始,但在美國是週日。我預計蘋果會考慮到當你談論N周開始的時候。 – Tommy

+0

這不起作用,我得到空回 – WDUK

+0

對不起,我以錯誤的方式得到日期。修正了 –

2

與日期有關的事情,你需要一個日曆。你的問題是假設公曆,但我建議你改變你的方法聲明:

- (NSString*)monthNameFromWeek:(NSInteger)week year:(NSInteger)year calendar:(NSCalendar*)cal; 

由此看來,還有我們正在談論這一天的模糊性。例如(這沒有被檢查),2015年第4周可能包含1月和2月。哪一個是正確的?在這個例子中,我們將使用星期幾(表示星期日)的工作日(在英國格里曆日曆中),我們將使用這個月的任何月份。

因此,您的代碼將是:

// Set up our date components 
NSDateComponents* comp = [[NSDateComponents alloc] init]; 
comp.year = year; 
comp.weekOfYear = week; 
comp.weekday = 1; 

// Construct a date from components made, using the calendar 
NSDate* date = [cal dateFromComponents:comp]; 

// Create the month string 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"MMMM"]; 
return [dateFormatter stringFromDate:date]; 
相關問題