0

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.

Shaig Khaligli
  • 4,955
  • 5
  • 22
  • 32
Navneet Sharma
  • 111
  • 1
  • 1
  • 12
  • 1
    Possible duplicate of [How do I get the day of the week with Cocoa Touch?](http://stackoverflow.com/questions/4269093/how-do-i-get-the-day-of-the-week-with-cocoa-touch) – kb920 Oct 10 '16 at 08:33

2 Answers2

5

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

Rajan Maheshwari
  • 14,465
  • 6
  • 64
  • 98
  • if i have a day of the year say 111th day how can i retrieve it as 21-04-2018 – Xcodian Solangi Apr 21 '18 at 06:03
  • 1
    You forgot to mention that Sunday is 1. – Vyachaslav Gerchicov Aug 07 '20 at 13:40
  • @XcodianSolangi I am very late to the party. But if you want to do something like retrieving the date from day number. Just take the date as 1 Jan 2018 and add 111 days. This will yield you a new Date. Explore the Calendar.current.date(byAdding...) method. Here is the link in case you are interested. https://stackoverflow.com/a/5067868/2545465 – Rajan Maheshwari Aug 14 '20 at 21:10
0

Use this

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponent = [calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitWeekday ) fromDate:[NSDate date] ];
NSNumber *weekNo = [NSNumber numberWithInteger:dateComponent. weekday];
pkamb
  • 33,281
  • 23
  • 160
  • 191
balkaran singh
  • 2,754
  • 1
  • 17
  • 32