gpt4 book ai didi

swift3 - 如何在 Swift 中将本周的第一天设置为星期二?

转载 作者:行者123 更新时间:2023-12-04 13:36:45 25 4
gpt4 key购买 nike

如何在 Swift 3 中将本周的第一天设置为星期二?时间表将在每周二更新,因此第一天必须从周二开始。

然后在标签上显示:

thisWeekDate.text! = "\(first day of current week) - \(last day of current week)"

完整代码。
let today = NSDate()
let nextTue = Calendar.current.date(byAdding: .day, value: 6, to: today as Date)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let todayString = formatter.string(from: today as Date)
let nextString = formatter.string(from: nextTue!)
formatter.dateFormat = "dd-MMM-yyyy"

let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let components = calendar!.components([.weekday], from: today as Date)

//Label code
thisWeekDate.text! = "\(first day of current week) - \(last day of current week)"

//If i can change the first day of current week this weekly update code can be deleted
if components.weekday == 3 {
print("Hello Tuesday")
thisWeekDate.text! = "\(todayString) - \(nextString)"

UserDefaults.standard.set(todayString, forKey: "todayStringKey")
_ = UserDefaults.standard.object(forKey: "todayStringKey") as? String
UserDefaults.standard.set(nextString, forKey: "nextStringKey")
_ = UserDefaults.standard.object(forKey: "nextStringKey") as? String

} else {
print("It's not Tuesday")
let RetrivedDate_1 = UserDefaults.standard.object(forKey: "todayStringKey") as? String
let RetrivedDate_2 = UserDefaults.standard.object(forKey: "nextStringKey") as? String

if let date_1 = RetrivedDate_1, let date_2 = RetrivedDate_2 {
thisWeekDate.text! = "\(date_1) - \(date_2)"
}


}

应用设计截图

App design screenshot

最佳答案

创建自定义公历并将第一个工作日设置为星期二

var customCalendar = Calendar(identifier: .gregorian)
customCalendar.firstWeekday = 3

然后你可以得到周间隔
var startDate = Date()
var interval = TimeInterval()
customCalendar.dateInterval(of: .weekOfMonth, start: &startDate, interval: &interval, for: Date())
let endDate = startDate.addingTimeInterval(interval - 1)
print(startDate, endDate)

关于swift3 - 如何在 Swift 中将本周的第一天设置为星期二?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45810305/

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