【问题标题】:how counting down the days in swift?如何快速倒计时?
【发布时间】:2021-01-26 09:13:28
【问题描述】:

我是 Swift 新手,还没有使用过 NSDate。对于我的应用程序,我需要如何计算距离活动还有多少天。事件的日期是用 Firebase 上的 DatePicker 编写的,我需要从当前日期计算距离编写日期还有多少天。我需要的只是倒计时。

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    将您的数据从 DatePicker 转换为 Date 对象,您可以使用以下函数返回 Int,表示已过日期的天数。

    func daysTo(date: Date) -> Int? {
        let calendar = Calendar.current
    
        let date1 = calendar.startOfDay(for: Date())
        let date2 = calendar.startOfDay(for: date)
    
        let components = calendar.dateComponents([.day], from: date1, to: date2)
        return components.day
    }
    

    【讨论】:

    【解决方案2】:

    您可以使用此扩展来查找日期之间的差异:

    extension Date {
        
        public func diffrenceTime() -> (Int, Int) {
            var cal = Calendar.init(identifier: .persian)
            let d1 = Date()
            let components = cal.dateComponents([.hour, .minute], from: self, to: d1)
            let diffHour = components.hour!
            let diffMinute = components.minute!
            
            return (diffHour, diffMinute)
        }
        
        public func fullDistance(from date: Date, resultIn component: Calendar.Component, calendar: Calendar = .current) -> Int? {
            calendar.dateComponents([component], from: self, to: date).value(for: component)
        }
    
        public func distance(from date: Date, only component: Calendar.Component, calendar: Calendar = .current) -> Int {
            let days1 = calendar.component(component, from: self)
            let days2 = calendar.component(component, from: date)
            return days1 - days2
        }
    
        public func hasSame(_ component: Calendar.Component, as date: Date) -> Bool {
            self.distance(from: date, only: component) == 0
        }
    }
    

    使用示例:

    let dateOne = Date() // or any date
                let dateTwo = getDateFromServer // your second date for
                
                // option One
                let distanceDay = dateOne.fullDistance(from: dateTwo, resultIn: .day)
                
                var cal = Calendar.current // for your calendar
                cal.locale = Locale.init(identifier: "EN")
                // option Two
                let distanceDay = dateOne.fullDistance(from: dateTwo, resultIn: .day, calendar: cal)
    

    您可以在结果参数中设置小时、分钟或任何组件来查找差异而不是天

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-28
      • 2016-12-16
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      相关资源
      最近更新 更多