Skip to content

Commit 84c8490

Browse files
author
Josh Smith
committed
Improve date parsing with tips from @ole
Based on feedback in #5
1 parent ebdea73 commit 84c8490

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

json2swift/swift-code-templates.swift

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -67,24 +67,24 @@ private let codeTemplateForCreatableWithJSON = [
6767

6868
private let codeTemplateForDateParsing = [
6969
"extension Date {",
70-
" // Date parsing is serialized on a dedicated queue because DateFormatter is not thread-safe.",
71-
" private static let parsingQueue = DispatchQueue(label: \"JSONDateParsing\")",
70+
" // Date formatters are cached because they are expensive to create. All cache access is performed on a serial queue.",
71+
" private static let cacheQueue = DispatchQueue(label: \"DateFormatterCacheQueue\")",
7272
" private static var formatterCache = [String: DateFormatter]()",
7373
" private static func dateFormatter(with format: String) -> DateFormatter {",
7474
" if let formatter = formatterCache[format] { return formatter }",
7575
" let formatter = DateFormatter()",
7676
" formatter.dateFormat = format",
77+
" formatter.locale = Locale(identifier: \"en_US_POSIX\")",
78+
" formatter.calendar = Calendar(identifier: .gregorian)",
79+
" formatter.timeZone = TimeZone(secondsFromGMT: 0)! // UTC is assumed, but won't interfere with a format-specified time zone.",
7780
" formatterCache[format] = formatter",
7881
" return formatter",
7982
" }",
8083
"",
8184
" static func parse(string: String, format: String) -> Date? {",
82-
" var date: Date?",
83-
" parsingQueue.sync {",
84-
" let formatter = dateFormatter(with: format)",
85-
" date = formatter.date(from: string)",
86-
" }",
87-
" return date",
85+
" var formatter: DateFormatter!",
86+
" cacheQueue.sync { formatter = dateFormatter(with: format) }",
87+
" return formatter.date(from: string)",
8888
" }",
8989
"",
9090
" init?(json: [String: Any], key: String, format: String) {",

0 commit comments

Comments
 (0)