27
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Swift4】Date()の9時間のズレを調整【Date】

Last updated at Posted at 2017-12-28

Date()はGMTベースなので日本では9時間ズレます。
単純にシステム日時が欲しい時のためにメソッドをひとつ追加します。

Dateを拡張

extension Date {
    
    func toStringWithCurrentLocale() -> String {

        let formatter = DateFormatter()
        formatter.timeZone = TimeZone.current
        formatter.locale = Locale.current
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        return formatter.string(from: self)
    }

}

テスト

// 15時に実行

let date = Date()
print(date)
print(date.toStringWithCurrentLocale())

// 2017-12-28 06:00:30 +0000
// 2017-12-28 15:00:30
27
22
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
27
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?