Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

objective c - Get the Week Number in iOS SDK

I want to get the Week number of the year from the date.I tried the code as follow but gives me a wrong week number.

My code for week number:

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
}

Note: If i try with with [NSDate date] display the correct.

Help me to solve this.. Thank you,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ObjectiveC:

 NSCalendar *calendar = [NSCalendar currentCalendar];
 NSDateComponents *dateComponent = [calendar components:(NSWeekOfYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];
 NSLog(@"%@",dateComponent);

Update

 NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:date];
    NSLog(@"%@",dateComponent);

Swift:

let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components([.WeekOfYear, .Day, .Month, .Year], fromDate: NSDate(timeIntervalSinceNow: 0))
print("weekOfYear (dateComponent.weekOfYear)")

Swift 3 - Swift 5:

let component = Calendar.current.component(.weekOfYear, from: Date())
print("Week of Year (component)")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...