数天 - iOS/Swift

count days - iOS/Swift

我正在尝试为 days 制作一个计数器,以便用户可以知道 he/she 在哪一天。

我有开始和结束日期,我有开始和结束之间的计数 我想要的是告诉用户他现在是哪一天(第 1 天,第 2 天,第 3 天......)

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

有什么帮助吗?

试试这个:

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
}

希望这对您有所帮助:

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.")
}