gpt4 book ai didi

ios - 如何将日期范围格式化为 "MMM, d"?

转载 作者:行者123 更新时间:2023-11-28 13:53:44 27 4
gpt4 key购买 nike

我正在尝试显示当前日期的周数,以及周数的日期范围。现在日期范围格式是日期时间,我想将其更改为“1 月 13 日”。关于如何解决这个问题的任何建议?

override func viewDidLoad() {
super.viewDidLoad()


let dateToday = Date()
let weekNumber = NSCalendar.current.component(.weekOfYear, from: dateToday)
let weekRange = dayRangeOf(weekOfYear: weekNumber, for: dateToday)

weekLabel.text = String("Week #\(weekNumber): \(weekRange)")
}

func dayRangeOf(weekOfYear: Int, for date: Date) -> Range<Date>
{
let calendar = Calendar.current
let year = calendar.component(.yearForWeekOfYear, from: date)
let startComponents = DateComponents(weekOfYear: weekOfYear, yearForWeekOfYear: year)
let startDate = calendar.date(from: startComponents)!
let endComponents = DateComponents(day:7, second: -1)
let endDate = calendar.date(byAdding: endComponents, to: startDate)!
return startDate..<endDate
}

最佳答案

有一个专门的 API 来显示日期间隔:DateIntervalFormatter

let intervalForatter = DateIntervalFormatter()
intervalFormatter.timeStyle = .none
intervalFormatter.dateStyle = .medium
weekLabel.text = String("Week #\(weekNumber): \(intervalFormatter.string(from: weekRange.lowerBound, to: weekRange.upperBound))")

您还可以使用自定义日期格式(顺便说一下,1 月 13 日是 MMM d)

let intervalFormatter = DateIntervalFormatter()
intervalFormatter.dateTemplate = "MMM d"
let text = String("Week #\(weekNumber): \(intervalFormatter.string(from: weekRange.lowerBound, to: weekRange.upperBound))")

关于ios - 如何将日期范围格式化为 "MMM, d"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54171944/

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