I am trying to display the week number of current date, and the date range of the week number. Right now the date range format is DateTime, I would like to change it to "Jan 13"instead. Any recommendations on how I can fix this?
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
}
You can user answer from: Date Format in Swift
There is a dedicated API to display date intervals:
DateIntervalFormatter
You can also use a custom date format (by the way Jan 13 is
MMM d
)