搜索完SO后,除了this question之外,我找不到解决方案。我正在考虑创建将接受数周的int
和今年int
这将与月份的名称返回NSString
的方法:将某一年份的周编号转换为月份名称
- (NSString *)getMonthNameFromNumber:(int)weekNumber andYear:(int)year
但我不能找到解决这个问题的方法。如果有人能提供建议,会很高兴。
搜索完SO后,除了this question之外,我找不到解决方案。我正在考虑创建将接受数周的int
和今年int
这将与月份的名称返回NSString
的方法:将某一年份的周编号转换为月份名称
- (NSString *)getMonthNameFromNumber:(int)weekNumber andYear:(int)year
但我不能找到解决这个问题的方法。如果有人能提供建议,会很高兴。
像这样的事情会做
注意,这是依赖于设备的偏好设置当前日历。
如果这不符合您的需要,您可以提供一个NSCalendar
实例并使用它来检索日期而不是使用currentCalendar
。通过这样做,您可以配置诸如哪一天是一周的第一天等等。 NSCalendar
的documentation值得一读。
如果使用自定义日历是一种常见的情况下,只是改变了实施类似
- (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
的方法名,除非你正在返回间接的价值。
与日期有关的事情,你需要一个日历。你的问题是假设公历,但我建议你改变你的方法声明:
- (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];
NSDateComponents可能是有用的。 – Larme
使用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 –