2016-11-01 154 views
1

我是iOS和編程的新手,我需要以某種方式獲取從當前月份的第一天到今天的數組。和過去3個月至今的陣列,但我不知道該怎麼做,請任何幫助或想法?獲取從一個月的第一天到今天的陣列天Swift

我查了一下這個獲得本月的第一天:

extension Date { 
func startOfMonth() -> Date? { 
    let comp: DateComponents = Calendar.current.dateComponents([.year, .month, .hour], from: Calendar.current.startOfDay(for: self)) 
    return Calendar.current.date(from: comp)! 
} 

,但它只能在一個視圖控制器,如果做的事在我的項目的另一部分?而且我不知道如何遍歷數組來獲取所有的第一天,今天的天...

編輯

我做了這樣的事情,但它給馬一個無限循環..我究竟做錯了什麼?

func weatherDatesFromCurrentDayMonth() -> [Any] { 
    var date = Date() 
    let currentCalendar = Calendar.current 
    var dateComponents = DateComponents() 
    dateComponents.month = -1 
    // dateComponents.day = 1 
    let endingDate = Calendar.current.date(byAdding: dateComponents, to: date) 
    print("\(endingDate!)") 
     var datesArray = Array<Any>() 

    while date.compare(endingDate!) != ComparisonResult.orderedAscending 
    { 
     var dateComponents = DateComponents() 
     dateComponents.day = 1 
     date = Calendar.current.date(byAdding: dateComponents, to: date)! 
     datesArray.append(date) 
     print("\(datesArray)") 
    } 

    return [datesArray] 

} 

回答

1

你有無限循環,因爲一開始你endingDate已經是一個月前和date就是現在。由於循環內只增加date它不會永遠是endingDate後,因此您的病情始終true

試試這個代碼:

func weatherDatesFromCurrentDayMonth() -> [Date] { 
    let now = Date() 
    var currentDate = previousMonth(date: now) 
    var datesArray = [Date]() 

    while currentDate < now { 
     datesArray.append(currentDate) 
     currentDate = nextDay(date:currentDate) 
    } 
    print("result: \(datesArray)") 
    return datesArray 
} 

func nextDay(date: Date) -> Date { 
    var dateComponents = DateComponents() 
    dateComponents.day = 1 
    return Calendar.current.date(byAdding: dateComponents, to: date)! 
} 

func previousMonth(date: Date) -> Date { 
    var dateComponents = DateComponents() 
    dateComponents.month = -1 
    return Calendar.current.date(byAdding: dateComponents, to: date)! 
}