LoginSignup
11
10

More than 5 years have passed since last update.

NSDateFormatterの正しい使い方

Last updated at Posted at 2015-04-03

追記:何故この記事を見つけられなかったのか…
NSDateFormatterで検索したら一番上に出てきてすごく分かりやすくまとまっている。


"NSDateFormatter"でGoogle検索すると、dateFormatを指定して使う方法ばかり出てくる。
だから、それが普通の使い方だと信じて疑わない人が多いのではないだろうか。
僕は、5分前までそう信じていた。

NSDateFormatterを使って時間を表示したい場合、開発者の思い通りのフォーマットで表示したい場合というのは極限られた場合だと思う。
多くの場合、ユーザの設定した通りの表示方法で表示したいはず。
その場合は、以下の実装方法が正しい。

MyViewController.swift
class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        let formatter = NSDateFormatter()
        formatter.dateStyle = NSDateFormatterStyle.ShortStyle
        formatter.timeStyle = NSDateFormatterStyle.ShortStyle
        let date = NSDate()
        label.text = formatter.stringFromDate(date)
    }
}

これは現在時刻を、
2015/04/03 18:33
のような形で表示する。

NSDateFormatterStyleには、5種類の値がある。

  • NoStyle
  • ShortStyle
  • MediumStyle
  • LongStyle
  • FullStyle

の5つ。
デフォルト値はNoStyle。
NoStyleのときは、その項目は表示されない。

それぞれ、どのように表示されるかは、別の記事にまとめた。

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10