Skip to content

Commit

Permalink
Improve date parsing with tips from @ole
Browse files Browse the repository at this point in the history
Based on feedback in #5
  • Loading branch information
Josh Smith committed Nov 8, 2016
1 parent ebdea73 commit 84c8490
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions json2swift/swift-code-templates.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,24 +67,24 @@ private let codeTemplateForCreatableWithJSON = [

private let codeTemplateForDateParsing = [
"extension Date {",
" // Date parsing is serialized on a dedicated queue because DateFormatter is not thread-safe.",
" private static let parsingQueue = DispatchQueue(label: \"JSONDateParsing\")",
" // Date formatters are cached because they are expensive to create. All cache access is performed on a serial queue.",
" private static let cacheQueue = DispatchQueue(label: \"DateFormatterCacheQueue\")",
" private static var formatterCache = [String: DateFormatter]()",
" private static func dateFormatter(with format: String) -> DateFormatter {",
" if let formatter = formatterCache[format] { return formatter }",
" let formatter = DateFormatter()",
" formatter.dateFormat = format",
" formatter.locale = Locale(identifier: \"en_US_POSIX\")",
" formatter.calendar = Calendar(identifier: .gregorian)",
" formatter.timeZone = TimeZone(secondsFromGMT: 0)! // UTC is assumed, but won't interfere with a format-specified time zone.",
" formatterCache[format] = formatter",
" return formatter",
" }",
"",
" static func parse(string: String, format: String) -> Date? {",
" var date: Date?",
" parsingQueue.sync {",
" let formatter = dateFormatter(with: format)",
" date = formatter.date(from: string)",
" }",
" return date",
" var formatter: DateFormatter!",
" cacheQueue.sync { formatter = dateFormatter(with: format) }",
" return formatter.date(from: string)",
" }",
"",
" init?(json: [String: Any], key: String, format: String) {",
Expand Down

0 comments on commit 84c8490

Please sign in to comment.