I'm looking for a possibility in Xcode to get a label count town the days until Christmas. I tried to count down the days with the NSDate Foundation but didn't achieve a solution :(
This countdown is a present or someone and I appreciate every example code from you!
Thanks in advance! Benjamin
The code I tried was from a older video but didn´t work out for me... Can someone tell me why and how I can fix it?
Code:
import UIKit
class StartViewController: UIViewController {
@IBOutlet weak var dateLabelOutlet: UILabel!
let formatter = DateFormatter()
let userCalendar = NSCalendar.current
let requestedComponents: NSCalendar.Unit = [
NSCalendar.Unit.Month,
NSCalendar.Unit.Day,
NSCalendar.Unit.Hour,
NSCalendar.Unit.Minute,
NSCalendar.Unit.Second
]
func printTime(){
formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
let startTime = NSDate()
let endTime = formatter.date(from: "12/24/18 12:00:00 a")
let timeDifference = userCalendar.dateComponents(requestedComponents, from: startTime, to: endTime!, options: [])
}
}
This method calculates and prints the number of days from today until next Christmas
func printDays() {
// create date components of 12/24
let xmasComponents = DateComponents(month: 12, day: 24)
// get next occurrence
let nextXmas = Calendar.current.nextDate(after: Date(), matching: xmasComponents, matchingPolicy: .strict)!
// calculate number of days
let daysUntilXmas = Calendar.current.dateComponents([.day], from: Date() , to: nextXmas).day!
print("Christmas is in \(daysUntilXmas) days")
}