距离下一次生日还有多少天计算 (Swift 3)

提出一个问题,已知一个人的公历生日(简单点),算距离他最近生日还剩多少天?

//计算距离生日时间(有个小问题,都是用UTC而非本地时区处理的)
func calcunateCuntdownDays(birthday: String) -> Int {
    let defaultDateFormatter = DateFormatter()
    defaultDateFormatter.locale = Locale.current
    //返回值 countDown
    var countDown = 0
    // 1. 获取当前日期
    let currentDay = Date()
    //print(currentDay)
    // 2. 组建当年生日
    defaultDateFormatter.dateFormat = "yyyy"
    let currentYear = defaultDateFormatter.string(from: currentDay)
    var newBirthdayString = birthday
    newBirthdayString.replaceSubrange(newBirthdayString.startIndex ..< newBirthdayString.index(newBirthdayString.startIndex, offsetBy: 4), with: currentYear)
    defaultDateFormatter.dateFormat = "yyyy-MM-dd"
    let birthDay = defaultDateFormatter.date(from: newBirthdayString)
    //print(birthDay)
    // 3. 比较两个日期
    if let birthDay = birthDay {
        if birthDay <= currentDay {
            //4.1 如果生日已过,加一年,生成新的生日
            let yearsToAdd = 1
            var newDateComponent = DateComponents()
            newDateComponent.year = yearsToAdd
            let newBirthDay = Calendar.current.date(byAdding: newDateComponent, to: birthDay)
            // 5 计算差值
            countDown = compare2Date(FromDate: currentDay, ToDate: newBirthDay!)
        }else {
            countDown = compare2Date(FromDate: currentDay, ToDate: birthDay)
        }
    }
    return countDown
}

//计算两个日期差天数
func compare2Date(FromDate: Date, ToDate: Date) -> Int {
    var result = 0
    let interval = ToDate.timeIntervalSince(FromDate)
    result = Int(round(interval / 86400.0))
    
    return result
}
Comments
Write a Comment