Xcode Countdown天数直到圣诞节

时间:2018-11-18 15:43:17

标签: ios swift4 xcode10

我正在寻找Xcode的可能性,以在圣诞节前几天获得一个标签计数镇。我试图倒数NSDate Foundation的日子,但没有实现解决方案:(

此倒数是礼物或礼物,我感谢您提供的每个示例代码!

提前谢谢! 本杰明

我尝试的代码来自较旧的视频,但对我而言却不起作用...有人可以告诉我为什么以及如何解决该问题吗?

代码:

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: [])     
    }
}

1 个答案:

答案 0 :(得分:0)

此方法计算并打印从今天到下个圣诞节的天数

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