如何在一个 iOS 应用中展示当前日期和时间?
在任何编程语言中玩弄日期和时间非常重要,如果你正在开发移动应用就更加重要了。
天气、预测和游戏等海量的应用都需要用到日期和时间。我们将在本教程中讲解如何获取当前日期和时间。
获取当前日期和时间的实例属性是 timeIntervalSince1970,你可以访问 https://developer.apple.com/documentation/foundation/nsdate/1407504-timeintervalsince1970 了解详情。
因此,将以下代码复制到你的 viewDidLoad 方法中并运行该应用,我们将打印当前日期和时间,并且在需求的基础上,我们可以在 storyboard 中将此打印到 UILabel 中。
override func viewDidLoad() { super.viewDidLoad() let timestamp = NSDate().timeIntervalSince1970 let timeInterval = TimeInterval(timestamp) let currenTime = NSDate(timeIntervalSince1970: TimeInterval(timeInterval)) print(currenTime) }
广告