我创建了一个方法,该方法应该采用“ YYYY-MM- DD”形式的字符串,并吐出一个int,该int表示相对于它所在的星期的日期位置(无论两个月之间是否重叠)。因此,例如,sunday = 1 monday = 2,依此类推。
这是我的代码:
func getDayOfWeek(today:String)->Int{ var formatter:NSDateFormatter = NSDateFormatter() formatter.dateFormat = "YYYY-MM-DD" var todayDate:NSDate = formatter.dateFromString(today)! var myCalendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar) var myComponents = myCalendar.components(NSCalendarUnit.WeekdayOrdinalCalendarUnit, fromDate: todayDate) var weekDay = myComponents.weekdayOrdinal return weekDay }
我知道这NSCalendarUnit.WeekdayOrdinalCalendar是错误的,但是我尝试了大多数逻辑组合。并且也搞砸了myComponents.weekdayOrdinal二手mycomponents.day或二手.weekday。
NSCalendarUnit.WeekdayOrdinalCalendar
myComponents.weekdayOrdinal
mycomponents.day
.weekday
这是我使用方式的选择:
static var EraCalendarUnit: NSCalendarUnit { get } static var YearCalendarUnit: NSCalendarUnit { get } static var MonthCalendarUnit: NSCalendarUnit { get } static var DayCalendarUnit: NSCalendarUnit { get } static var HourCalendarUnit: NSCalendarUnit { get } static var MinuteCalendarUnit: NSCalendarUnit { get } static var SecondCalendarUnit: NSCalendarUnit { get } static var WeekCalendarUnit: NSCalendarUnit { get } static var WeekdayCalendarUnit: NSCalendarUnit { get } static var WeekdayOrdinalCalendarUnit: NSCalendarUnit { get } static var QuarterCalendarUnit: NSCalendarUnit { get } static var WeekOfMonthCalendarUnit: NSCalendarUnit { get } static var WeekOfYearCalendarUnit: NSCalendarUnit { get } static var YearForWeekOfYearCalendarUnit: NSCalendarUnit { get } static var CalendarCalendarUnit: NSCalendarUnit { get } static var TimeZoneCalendarUnit: NSCalendarUnit { get }
我不清楚,因为没有DayOfWeekUnit选项(或类似的东西)。
您正在寻找的是(如果我对问题的理解正确的话)NSCalendarUnit.CalendarUnitWeekday。的对应属性NSDateComponents是weekday。
NSCalendarUnit.CalendarUnitWeekday
NSDateComponents
weekday
另请注意,您的日期格式不正确(可以在此处找到完整的规范:http : //unicode.org/reports/tr35/tr35-6.html)。
使用自动类型推断可以稍微简化该函数,在常量足够的情况下,也可以大量使用变量。另外,该函数应返回nil 用于无效输入字符串的可选参数。
nil
更新了 Swift 3及更高版本的 代码 :
func getDayOfWeek(_ today:String) -> Int? { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" guard let todayDate = formatter.date(from: today) else { return nil } let myCalendar = Calendar(identifier: .gregorian) let weekDay = myCalendar.component(.weekday, from: todayDate) return weekDay }
例:
if let weekday = getDayOfWeek("2014-08-27") { print(weekday) } else { print("bad input") }
Swift 2的 原始答案 :
func getDayOfWeek(today:String)->Int? { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" if let todayDate = formatter.dateFromString(today) { let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let myComponents = myCalendar.components(.Weekday, fromDate: todayDate) let weekDay = myComponents.weekday return weekDay } else { return nil } }