当前位置 : 主页 > 手机开发 > 其它 >

swift – 获取没有WeekCalendarUnit的一周的第一天

来源:互联网 收集:自由互联 发布时间:2021-06-11
我希望在一周的第一天取决于NSDate. 它工作正常,但我有一个警告,因为不推荐使用WeekCalendarUnit. 我做了一些研究,我试图用以下代码替换WeekCalendarUnit: static var CalendarUnitWeekday: NSCalendarUn
我希望在一周的第一天取决于NSDate.

它工作正常,但我有一个警告,因为不推荐使用WeekCalendarUnit.

我做了一些研究,我试图用以下代码替换WeekCalendarUnit:

static var CalendarUnitWeekday: NSCalendarUnit { get }
static var CalendarUnitWeekdayOrdinal: NSCalendarUnit { get }
static var CalendarUnitWeekOfMonth: NSCalendarUnit { get }
static var CalendarUnitWeekOfYear: NSCalendarUnit { get }

但我没有相同的结果.这是我的垃圾代码:

var date = NSDate()
dateFormatter.dateFormat = "dd/YY"
let calendar = NSCalendar.currentCalendar()
let currentDateComponents = calendar.components(.CalendarUnitYear | .WeekCalendarUnit , fromDate: date)
let startOfWeek = calendar.dateFromComponents(currentDateComponents)
var dteString = dateFormatter.stringFromDate(startOfWeek!)
// Output is "17/15"

任何的想法?

您可以结合使用.CalendarUnitWeekOfYear
.CalendarUnitYearForWeekOfYear,这应该给出预期的结果:

let currentDateComponents = calendar.components(.CalendarUnitYearForWeekOfYear | .CalendarUnitWeekOfYear , fromDate: date)
let startOfWeek = calendar.dateFromComponents(currentDateComponents)

或者,使用rangeOfUnit()(我个人觉得更容易
使用):

var startOfWeek : NSDate?
calendar.rangeOfUnit(.CalendarUnitWeekOfYear, startDate: &startOfWeek, interval: nil, forDate: date)

在Swift 2中,这必须改为

let currentDateComponents = calendar.components([.YearForWeekOfYear, .WeekOfYear ], fromDate: date)
let startOfWeek = calendar.dateFromComponents(currentDateComponents)

var startOfWeek : NSDate?
calendar.rangeOfUnit(.WeekOfYear, startDate: &startOfWeek, interval: nil, forDate: date)
网友评论