Swift 斯威夫特:日期选择器计时器?
嘿强> 我的问题是: 因此,我有一个日期选择器,主要用于在达到设定时间时发送消息。但是,我希望看到时间用完(类似计时器),直到达到时间。最佳格式(hh:mm:ss),因为日期选择器设置为计时器格式 我只是编程的初学者。所以我不知道该怎么办:/ 如果有人能帮助我,我会非常高兴的 非常感谢Swift 斯威夫特:日期选择器计时器?,swift,xcode,timer,datepicker,countdown,Swift,Xcode,Timer,Datepicker,Countdown,嘿 我的问题是: 因此,我有一个日期选择器,主要用于在达到设定时间时发送消息。但是,我希望看到时间用完(类似计时器),直到达到时间。最佳格式(hh:mm:ss),因为日期选择器设置为计时器格式 我只是编程的初学者。所以我不知道该怎么办:/ 如果有人能帮助我,我会非常高兴的 非常感谢 let date = NSDate() let calendar = Calendar.current let components = calendar.dateComponents
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"
首先,你不能写:
let competition = userCalendar.date(from: competitionDate as DateComponents)!
如果competitionDate
不是DateComponents
,而是Date
,则只会触发一个错误
然后,如果您只想用字符串表示时间量,那么
尝试:
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"