0
1

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 1 year has passed since last update.

【Swift】Dateは扱いにくい!!

Last updated at Posted at 2022-10-02

はじめに

Dateは扱いにくい!!
こんなふうに使いたい!!!

Date(string: "2022/05/10 12:00:00")

実装

extension Date {
    init(string: String, format: String = "yyyy/MM/dd HH:mm:ss") {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        dateFormatter.locale = Locale.current
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.calendar = Calendar(identifier: .gregorian)
        guard let date = dateFormatter.date(from: string) else {
            fatalError("The format is incorrect")
        }
        self.init(timeIntervalSince1970: date.timeIntervalSince1970)
    }
}

注意
dateFormatter.calendarを指定しないとユーザーの設定によって値が変わってしまう

https://qiita.com/SNQ-2001/items/38912a1f41129585cdba#comment-d114039a82f8abb99df9

おわり

fatalErrorで処理してるのは良くないかもしれないです。
おすすめの方法があればコメントで教えていただけると嬉しいです

0
1
2

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?