Vibhor Goyal
Vibhor Goyal

Reputation: 2425

How to find weekday from today's date using NSDate?

I know that I can figure out today's date by [NSDate date]; but how would I find out today day of the week, like Saturday, Friday etc.

I know that %w can be used in NSDateFormatter, but I don't know to use it.

Upvotes: 29

Views: 28480

Answers (6)

ArdenDev
ArdenDev

Reputation: 4191

Using this code

NSCalendar* currentCalendar = [NSCalendar currentCalendar];
NSDateComponents* dateComponents = [currentCalendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];

Assuming Sunday is 1 as mentioned in the AppleDoc does not work. The weekdays generated does not match with the regular calendar.

Going with Monday = 0 and Sunday = 7 works and matches with Apple Calendar

Do I need to do something else to match what's specified in Apple Docs.

Upvotes: 0

alita
alita

Reputation: 39

let today = Date()
let day = Calendar.current.dateComponents([.weekday], from: today).weekday
if ( day == 5)
    {
        yourText.text = "Thursday"
    }

Upvotes: 1

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19080

If someone is interested in a Swift solution, then use:

import Foundation

let weekday = NSCalendar.current.component(.weekday, from: Date())
print(weekday) // => prints the weekday number 1-7 (Sunday through Saturday) 

See the demo.

Update: fixed to work in Swift 3

Upvotes: 4

kennytm
kennytm

Reputation: 523284

NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comp = [cal components:NSCalendarUnitWeekday fromDate:[NSDate date]];
return [comp weekday]; // 1 = Sunday, 2 = Monday, etc.

See @HuguesBR's answer if you just need the weekday without other components (requires iOS 8+).

NSInteger weekday = [[NSCalendar currentCalendar] component:NSCalendarUnitWeekday 
                                                   fromDate:[NSDate date]];

(If you don't get a correct answer, check if you have mistyped NSCalendarUnitWeekday with other week-related components like NSCalendarUnitWeekdayOrdinal, etc.)


Swift 3:

let weekday = Calendar.current.component(.weekday, from: Date())
// 1 = Sunday, 2 = Monday, etc.

Upvotes: 80

Hugues BR
Hugues BR

Reputation: 2258

Shorter version

NSCalendarUnit dayOfTheWeek = [[NSCalendar currentCalendar] component:NSCalendarUnitWeekday fromDate:yourDate];

Upvotes: 1

Mobile Developer
Mobile Developer

Reputation: 5760

This is updated version valid for iOS 8

NSCalendar* currentCalendar = [NSCalendar currentCalendar];
NSDateComponents* dateComponents = [currentCalendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
return [dateComponents weekday];

Upvotes: 2

Related Questions