Что-то, как это будет делать
- (NSString *)monthNameForWeek:(NSUInteger)week inYear:(NSInteger)year {
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 = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
return [formatter stringFromDate:date];
}
Обратите внимание, что это зависит от текущего календаря, установленного в настройках устройства.
В случае, если это не соответствует вашим потребностям, вы можете предоставить экземпляр NSCalendar
и использовать его для получения даты вместо currentCalendar
. Поступая таким образом, вы можете настроить такие вещи, как первый день недели и т. Д. documentation из NSCalendar
стоит прочитать.
При использовании пользовательского календаря является общим случаем, просто изменить реализацию на что-то вроде
- (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
имен методов, если вы не возвращаются значение косвенно.
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 –