LoginSignup
0
2

More than 1 year has passed since last update.

【Swift】ミリ秒を含んだISO8601形式のデコード

Posted at

はじめに

現在、Zennの記事をウィジェットに一覧表示するアプリを作っています。
dateDecodingStrategyを使用してデコードしたかったのですが、ZennのDateはミリ秒まで表示されており、標準のISO8601ではデコードできませんでした。
ミリ秒を含んだISO8601形式でもデコードできるようにカスタムのiso8601Formatterを作成しました。

実装

// MARK: DateFormatter
private static let iso8601Formatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
    return formatter
}()

// MARK: JSONDecoder
private static let decoder: JSONDecoder = {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    decoder.dateDecodingStrategy = .formatted(iso8601Formatter)
    return decoder
}()

おわり

ISO8601DateFormatterを使用するときはオプションがあり、簡単にミリ秒にも対応ができました。

しかし、JSONDecoderではISO8601DateFormatterが使えないようです。

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