2013-08-29 108 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]; 
相关问题