Reputation: 1146
I am trying to implement a countdown to a specific date in swift getting days, hours, minutes, and seconds, but for some reason my implementation is returning the wrong amount of days until the event, but is returning the correct hours, minutes, and seconds. I'm not sure what's going wrong here:
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.second, .minute, .hour, .day], from: date as Date)
let currentDate = calendar.date(from: components)
let userCalendar = Calendar.current
let openingNight = NSDateComponents()
openingNight.year = 2020
openingNight.month = 9
openingNight.day = 10
openingNight.hour = 20
openingNight.minute = 30
openingNight.second = 0
let opener = userCalendar.date(from: openingNight as DateComponents)
let difference = calendar.dateComponents([.second, .minute, .hour, .day], from: currentDate!, to: opener!)
let daysLeft = difference.day
let hoursLeft = difference.hour
let minutesLeft = difference.minute
let secondsLeft = difference.second
daysLabel.text = "\(daysLeft!)"
hourLabel.text = "\(hoursLeft!)"
minuteLabel.text = "\(minutesLeft!)"
secondLabel.text = "\(secondsLeft!)"
it is returning 737661 days, 4 hours, 2 minutes, 28 seconds
Upvotes: 0
Views: 70
Reputation: 5741
The month and year are missing in the dataComponents for currentDate
. This will give the correct difference (it is still May 19 here, so 114 days until Sept 10).
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.second, .minute, .hour, .day, .month, .year], from: date as Date)
let currentDate = calendar.date(from: components)
let userCalendar = Calendar.current
let openingNight = NSDateComponents()
openingNight.year = 2020
openingNight.month = 9
openingNight.day = 10
openingNight.hour = 20
openingNight.minute = 30
openingNight.second = 0
let opener = userCalendar.date(from: openingNight as DateComponents)
let difference = calendar.dateComponents([.second, .minute, .hour, .day], from: currentDate!, to: opener!)
let daysLeft = difference.day
let hoursLeft = difference.hour
let minutesLeft = difference.minute
let secondsLeft = difference.second
print(difference) // day: 114 hour: 2 minute: 34 second: 6 isLeapMonth: false
Upvotes: 1