【Xcode/Swift】現在の日付 & 時刻を取得する方法


Storyboard


コード

import UIKit

class HomeViewController: UIViewController {

    @IBOutlet private weak var currentDateLabel: UILabel!
    @IBOutlet private weak var currentTimeLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func showCurrentDateAction(_ sender: Any) {
        currentDateLabel.text = "今日は\(getCurrentDate())です"
    }

    @IBAction func showCurrentTimeAction(_ sender: Any) {
        currentTimeLabel.text = "今は\(getCurrentTime())です"
    }

    // 日付と曜日を取得
    private func getCurrentDate() -> String {
        let date = NSDate()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy/MM/dd"
        let dateStr = formatter.string(from: date as Date)
        formatter.locale = NSLocale(localeIdentifier: "ja_JP") as Locale?
        formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "EEEEE", options: 0, locale: Locale.current)
        let weekStr = formatter.string(from: date as Date)
        return  dateStr + " (" + weekStr + ")"
    }

    // 現在時刻を取得
    private func getCurrentTime() -> String {
        let date = NSDate()
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss"
        return formatter.string(from: date as Date)
    }

}

☆参考文献