嘿!
我的问题是:
因此,我有一个数据报警器,它主要用于在到达设定时间时发送消息。但是,我希望看到时间耗尽(就像计时器一样),直到时间到达为止.最好采用这种格式(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"发布于 2020-06-16 16:21:12
首先,你不能写:
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"https://stackoverflow.com/questions/62411947
复制相似问题