2010-03-17 87 views
22

我知道我可以通過[NSDate date];弄清楚今天的日期,但我會如何找出一週的今天一天,像週六,日等如何使用NSDate從今天的日期查找週日?

我知道%w可以NSDateFormatter使用,但我不知道知道使用它。

+0

的可能的複製[我如何獲得可可觸摸星期幾?](http://stackoverflow.com/questions/4269093/how-do-i-get-the-day-of-the-week-with-cocoa-touch) – Suhaib 2016-10-05 04:08:02

回答

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

我們看看@HuguesBR的答案,如果你只需要無其他組件的工作日(需要iOS 8+)。

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

(如果你沒有得到正確的答案,請檢查您是否輸錯NSCalendarUnitWeekday與像NSCalendarUnitWeekdayOrdinal一週相關部件等)


斯威夫特3:

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

非常感謝肯尼。這工作完美。 – 2010-03-17 21:33:14

+3

comp weekday返回一個虛幻的巨大數字。 。 。 – coolcool1994 2013-06-02 11:46:06

+2

@ coolcool1994你可能會使用'NSWeekCalendarUnit' insted'NSWeekdayCalendarUnit' – enadun 2013-06-05 09:28:15

1

如果有人對Swift解決方案感興趣,請使用:

import Foundation 

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

查看demo

更新:固定在斯威夫特工作爲iOS 8

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

工作日是一個巨大的#?! – 2016-01-07 15:53:58

+0

可悲的是,這個答案對我來說不起作用。 – Suhaib 2016-10-05 17:10:42

+0

@Suhaib答案更新以匹配最新的Swift版本。感謝提到這個問題。 – 2016-10-06 05:34:11

1

這是更新的版本有效

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

較短的版本3

相關問題