gpt4 book ai didi

swift - 在没有 WeekCalendarUnit 的情况下获取一周的第一天

转载 作者:搜寻专家 更新时间:2023-10-31 21:53:40 24 4
gpt4 key购买 nike

我想根据 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)

关于swift - 在没有 WeekCalendarUnit 的情况下获取一周的第一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30330523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com