【问题标题】:Swift: DatePicker-Timer?斯威夫特:日期选择器定时器?
【发布时间】:2020-06-16 15:21:20
【问题描述】:

嘿!

这是我的问题:

所以我有一个日期选择器,主要用于在达到设定时间时发送消息。但是,我希望看到时间用完(类似计时器),直到时间到达。最好采用格式 (hh:mm:ss),因为日期选择器设置为计时器格式。

我只是编程的初学者。所以我不知道该怎么办:/

如果有人可以帮助我,我会很高兴!

非常感谢。

     let date = NSDate()
     let calendar = Calendar.current

     let components = calendar.dateComponents([.hour, .minute, .month, .year, .day], from: 
     date as Date)

     let currentDate = calendar.date(from: components)

     let userCalendar = Calendar.current

     let competitionDate = self.datepicker.isSelected

     let competition = userCalendar.date(from: competitionDate as DateComponents)!

     let CompetitionDifference = calendar.dateComponents([.hour, .minute, .second], from: 
     currentDate!, to: competition)


     let hoursLeft = CompetitionDifference.hour
     let minutesLeft = CompetitionDifference.minute
     let secondsLeft = CompetitionDifference.second

     print("hours:", hoursLeft ?? "N/A", "minutes:", minutesLeft ?? "N/A", "seconds:", 
     secondsLeft ?? "N/A")

    countDownLabel.text = "\(daysLeft ?? 0) hours, \(hoursLeft ?? 0) minutes, \(minutesLeft 
    ?? 0) seconds"

【问题讨论】:

    标签: swift xcode timer datepicker countdown


    【解决方案1】:

    首先,你不能写:

    let competition = userCalendar.date(from: competitionDate as DateComponents)!
    

    如果competitionDate 不是DateComponents 而是Date,它只会触发错误!

    那么,如果您只想要时间量的字符串表示,DateComponentsFormatter 适合您

    试试:

    let date = Date()
    let calendar = Calendar.current
    let userCalendar = Calendar.current
    
    let competitionDate = date + 4899
    let comps = userCalendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: competitionDate)
    
    
    
    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .full
    formatter.string(from: date, to: competitionDate) // "1 hour, 21 minutes, 39 seconds"
    formatter.unitsStyle = .short
    formatter.string(from: date, to: competitionDate) // "1 hr, 21 min, 39"secs"
    formatter.unitsStyle = .brief
    formatter.string(from: date, to: competitionDate) // "1hr 21min 39secs"
    formatter.unitsStyle = .abbreviated
    formatter.string(from: date, to: competitionDate) // "1h 21m 39s"
    formatter.unitsStyle = .positional
    formatter.string(from: date, to: competitionDate) // "1:21:39"
    formatter.includesTimeRemainingPhrase = true
    formatter.string(from: date, to: competitionDate) // "1:21:39 remaining"
    
    

    【讨论】:

      猜你喜欢
      • 2016-02-11
      • 1970-01-01
      • 2017-07-22
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      相关资源
      最近更新 更多