我正在努力制作一个计数器,因此用户可以知道他/她在哪一天。
我有开始和结束日期,我有开始和结束之间的计数 我想要的是告诉用户他在哪一天(第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 :(得分:1)
希望这会有所帮助:
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.")
}
答案 1 :(得分: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
}