我從其他線程中得到了一段代碼,但我想知道是否有人可以幫助我轉換此函數,以便以此格式打印出日期: 「DD-MM-YYYY」。目前它只是印刷一天。Swift 3函數在格式化後的字符串中輸出最近7天
func getLast7Dates()
{
let cal = Calendar.current
var date = cal.startOfDay(for: Date())
var days = [Int]()
for i in 1 ... 7 {
let day = cal.component(.day, from: date)
days.append(day)
date = cal.date(byAdding: .day, value: -1, to: date)!
}
print(days)
}
我知道我會需要使用:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
但我不知道在哪裏把它的功能,因爲這是我第一次使用日期。
感謝您的幫助:)
非常感謝。它工作完美,沒有改變太多以前的代碼,這太棒了!再次感謝:D – SwiftStarter
上面的代碼留下了一些需要。最好創建一個通用函數組合的解決方案(比如獲取最後7個日期,然後將其轉換爲字符串),而不是將它們混合爲一個。 – Alexander