2016-05-12 78 views
-1

我試圖爲天做一個計數器,所以用戶可以知道他/她在哪一天。計算天數 - iOS/Swift

img

我有開始和結束日期,我也開始之間的計數並終止 我要的是要告訴他時是什麼日子用戶(第1天,第2天,第3天.... )

let unit:NSCalendarUnit = [.Month, .Day] 
let components = cal!.components(unit, fromDate: startDate, toDate: endDate, options: []) 
var daysCount = components.day 
print(daysCount) 

有幫助嗎?

+0

如果你只想知道的天數,不計'.Month'。保留爲'[.Day]'。另外,如果你不想讓你的第一天成爲'day0',你可能想爲結果添加'1'。 – Sulthan

+0

謝謝,但我想要告訴用戶他是哪一天,例如(第1天...然後第二天---第2天......等) – ynamao

+0

什麼不適合你? – Sulthan

回答

0

希望這有助於:

let cal = NSCalendar.currentCalendar() 
let currentDate = NSDate() 

let startDate = currentDate.dateByAddingTimeInterval(-7 * 24 * 60 * 60) // 7 days ago 
let endDate = startDate.dateByAddingTimeInterval(10 * 24 * 60 * 60) // 10 days after start date (3 days from now) 

if endDate.compare(currentDate) == .OrderedDescending { 
    // end date is in the future 
    let components = cal.components(.Day, fromDate: startDate, toDate: currentDate, options: []) 
    let daysCount = components.day 
    print("\(daysCount) days passed.") 
} else { 
    // end date is now or in the past 
    let components = cal.components(.Day, fromDate: startDate, toDate: endDate, options: []) 
    let daysCount = components.day 
    print("\(daysCount) days passed. you reached the end date.") 
} 
+0

謝謝André! – ynamao

+0

不客氣 –

0

試試這個:

func daysFromDate(dateA: NSDate, toDate dateB: NSDate) -> Int { 
    let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)! 
    calendar.timeZone = NSTimeZone.localTimeZone() 
    calendar.locale = NSLocale.currentLocale() 
    return calendar.components([.Day], fromDate: dateA, toDate: dateB, options: .MatchStrictly).day 
}