How can I format Date range to “MMM, d”?

2020-05-07 19:05发布

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
}

标签: ios swift
2条回答
▲ chillily
2楼-- · 2020-05-07 19:40

You can user answer from: 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")
}
查看更多
3楼-- · 2020-05-07 19:49

There is a dedicated API to display date intervals: DateIntervalFormatter

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

You can also use a custom date format (by the way Jan 13 is MMM d)

let intervalFormatter = DateIntervalFormatter()
intervalFormatter.dateTemplate = "MMM d"
let text = String("Week #\(weekNumber): \(intervalFormatter.string(from: weekRange.lowerBound, to: weekRange.upperBound))")
查看更多
登录 后发表回答