How do I display the current date and time in an iOS application?


Playing with date and time is very important in any programming language, it becomes more important if you’re developing mobile application.

Numerous application such as weather, forecast, gaming and so on uses date and time. In this we will be seeing how we can get the current date and time.

To get the current date and time we will be using timeIntervalSince1970 instance property, you can read about it https://developer.apple.com/documentation/foundation/nsdate/1407504-timeintervalsince1970

So copy the below code in your viewDidLoad method and run the application, we will be printing the current date and time, and based on requirement we can print the same in UILabel in storyboard.

override func viewDidLoad() {
   super.viewDidLoad()
   let timestamp = NSDate().timeIntervalSince1970
   let timeInterval = TimeInterval(timestamp)
   let currenTime = NSDate(timeIntervalSince1970: TimeInterval(timeInterval))
   print(currenTime)
}

Updated on: 30-Jul-2019

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements