Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 480
user2526811 Avatar asked Jul 11 '13 07:07

user2526811


2 Answers

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)")
like image 54
Misha Vyrko Avatar answered Nov 06 '22 10:11

Misha Vyrko


[NSCalendar currentCalendar] gives you a Gregorian Calendar as default. You can use

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSISO8601Calendar];

to get an ISO 08601 conform calendar, which has week number 37 for your date.

like image 31
AlexVogel Avatar answered Nov 06 '22 09:11

AlexVogel