我刚刚开始使用Swift,我正在开发一个简单的应用程序,我希望用文本标签显示当前时间。
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:9)
使用日期格式化程序格式化日期。
var dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .MediumStyle
var timeString = "The time is: \(dateFormatter.stringFromDate(NSDate()))"
将timeString
设置为您的标签text
属性。在NSTimer
上运行它以使其保持最新状态。
答案 1 :(得分:6)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .medium
let timeString = "The time is: \(dateFormatter.string(from: Date() as Date))"
label.text = String(timeString)
let hour = calender.component(.hour, from: date)
let minute = calender.component(.minute, from: date)
let seconds = calender.component(.second, from: date)
label1.text = String(hour) + ":" + String(minute) + ":" + String(seconds)
label2.text = String(day) + ":" + String(month) + ":" + String(year)
答案 2 :(得分:5)
在标签中显示实时时间/日期。
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
dateLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .long, timeStyle: .none)
timeLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
}
@objc func tick() {
dateLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .long, timeStyle: .none)
timeLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
}
答案 3 :(得分:2)
Swift 4:
var currentDateTime = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .medium
yourLabel.text = "\(dateFormatter.string(from: currentDateTime))"