iOS Tutorials: Time & Date Format

This tutorials showcase some of the ways to display times and dates on your app. This could be an important feature if you would like the user to have access to the dates and time. In addition to that, you will be seeing live update of seconds where the seconds increases every second.

First, create a new project and depending what you would like to achieve first. I’ve included several labels on the storyboard to showcase the different results.

With the screenshot below, you could see the different date and time format displayed here.

The code below are some of example of the implementation that we will be using here.

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var firstLabel: UILabel!

 override func viewDidLoad() {
        super.viewDidLoad()
        firstLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .full, timeStyle: .full)
 }
}

This single code below here is powerful enough to change the format of the date and time. With the implementation of the following code, it will showcase in the following format:

.full                Tuesday, August 22, 2017 at 11:37:26AM Hawaiian-Aleutian Standard Time

.long              August 22, 2017 at 11:37:26AM HST

.medium       Aug 22, 2017, 11:37:26AM.

DateFormatter.localizedString(from: Date(), dateStyle: .full, timeStyle: .full)

However, this format only show a still format and the seconds doesn’t update itself every second. By creating a new function and also implementing Timer, it now shows the seconds that increases every seconds.

 override func viewDidLoad() {
        super.viewDidLoad()
        Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.updateTime), userInfo: nil, repeats: true)
    }

    func updateTime(){
        firstLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .full, timeStyle: .medium)
    }

 

 

 

  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*