我正在尝试显示当前日期的星期数和星期数的日期范围。现在日期范围格式为DateTime,我想改为将其更改为“ Jan 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
}
答案 0 :(得分:1)
有专用的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))")
答案 1 :(得分:0)
您可以从以下用户回答: Date Format in Swift
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MM d"
if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
print(dateFormatterPrint.string(from: date))
} else {
print("There was an error decoding the string")
}