我想从日期开始获取一年中的周数。我尝试了以下代码,但给出了错误的周数。
我的周代码:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSDate *date = [dateFormatter dateFromString:@"2012-09-15"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSLog(@"week: %i", [[calendar components: NSWeekOfYearCalendarUnit fromDate:date] weekOfYear]); //Display 38 instead of 37
}
注意:如果我尝试使用[NSDate date]
显示正确的。
帮我解决这个问题.. 谢谢,
答案 0 :(得分:17)
的ObjectiveC:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponent = [calendar components:(NSWeekOfYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];
NSLog(@"%@",dateComponent);
夫特:
let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components([.WeekOfYear, .Day, .Month, .Year], fromDate: NSDate(timeIntervalSinceNow: 0))
print("weekOfYear \(dateComponent.weekOfYear)")
斯威夫特3:
let component = Calendar.current.component(.weekOfYear, from: Date())
print("Week of Year \(component)")
答案 1 :(得分:11)
[NSCalendar currentCalendar]
默认为格里高利历。你可以使用
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSISO8601Calendar];
获取符合ISO 08601标准的日历,其日期 37 为您的日期。
答案 2 :(得分:0)
斯威夫特3:
您需要知道所选月份的最后Date
。比检查本周的周数,这将是您每月的周数
return Calendar.current.component(.weekOfMonth, from: lastDate ?? Date())
答案 3 :(得分:0)
ObjectiveC中更新的代码使用了Xcode版本 - 9.1 - :
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponent = [calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:[NSDate date]];
NSLog(@"%ld",(long)[dateComponent weekOfYear]);