2016-11-13 43 views
0

我從其他線程中得到了一段代碼,但我想知道是否有人可以幫助我轉換此函數,以便以此格式打印出日期: 「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" 

但我不知道在哪裏把它的功能,因爲這是我第一次使用日期。

感謝您的幫助:)

回答

1

設置格式化一次,在你的功能,按如下方式使用它之後,你的日期格式返回日期的陣列,並映射在他們(不是很多其他小的變化):

func getLast7Dates() 
{ 
    let cal = Calendar.current 
    let date = cal.startOfDay(for: Date()) 
    var days = [String]() 
    let dateFormatter = DateFormatter() 
    dateFormatter.dateFormat = "dd-MM-yyyy"  

    for i in 1 ... 7 { 
     let newdate = cal.date(byAdding: .day, value: -i, to: date)! 
     let str = dateFormatter.string(from: newdate) 
     days.append(str) 
    } 

    print(days) 
} 
+0

非常感謝。它工作完美,沒有改變太多以前的代碼,這太棒了!再次感謝:D – SwiftStarter

+1

上面的代碼留下了一些需要。最好創建一個通用函數組合的解決方案(比如獲取最後7個日期,然後將其轉換爲字符串),而不是將它們混合爲一個。 – Alexander

0

,而不是追加day到數組中,追加date

import Foundation 

func getLast7Dates() -> [Date] { 
    let today = Date() 

    var days = [Date]() 

    for i in 1 ... 7 { 
     let date = Calendar.current.date(byAdding: .day, value: -i, to: today)! 
     days.append(date) 
    } 

    return days 
} 

let dateFormatter = DateFormatter() 
dateFormatter.dateFormat = "dd-MM-yyyy" 

let dateStrings = getLast7Dates().map(dateFormatter.string(from:)) 

print(dateStrings) 

你可以使它更短:

func getLast7Dates() -> [Date] { 
    let today = Date() 

    return (-7 ... -1).map{ Calendar.current.date(byAdding: .day, value: $0, to: today)! 
    } 
} 
0

,你會想要使用此:

print(dateFormatter.stringFromDate(date)) 

此文檔是here

相關問題