Navneet Sharma
Navneet Sharma

Reputation: 111

How to get Day number of week from NSDate

I want to know the day number of week from NSDate.

Example:- Suppose today is 10th Oct 2016, Here Week number is 3rd which i got using

NSInteger week = [_calendar component:NSCalendarUnitWeekOfMonth fromDate:date];

Now I want to know the day number of current week, Which is 2nd for 10th Oct.

Upvotes: 0

Views: 1330

Answers (2)

Rajan Maheshwari
Rajan Maheshwari

Reputation: 14571

It will fetch you the day number i.e. 2. The day number are always same for every week. (1-7).

As pointed by Vyachaslav Gerchicov, the weekday number starts from Sunday
i.e Sunday is 1, Monday is 2... Saturday is 7

//Assuming your calendar is initiated like this
NSCalendar *_calendar = [NSCalendar currentCalendar];

//Fetch the day number
NSInteger day = [_calendar component:NSCalendarUnitWeekday fromDate:date];

Explore NSCalendar for more details here


For Swift 5.x

let day = Calendar.current.component(.weekday, from: date)

Explore Calendar for more details here

Upvotes: 5

balkaran singh
balkaran singh

Reputation: 2786

Use this

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponent = [calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitWeekday ) fromDate:[NSDate date] ];
NSNumber *weekNo = [NSNumber numberWithInteger:dateComponent. weekday];

Upvotes: 0

Related Questions