-
Notifications
You must be signed in to change notification settings - Fork 85
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #408 from donnywals/reuse-dateformatters
Reuse date formatters
- Loading branch information
Showing
3 changed files
with
47 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// | ||
// DateFormatterCache.swift | ||
// Contentful | ||
// | ||
// Created by Donny Wals on 05/08/2024. | ||
// | ||
|
||
import Foundation | ||
|
||
class DateFormatterCache { | ||
static let shared = DateFormatterCache() | ||
|
||
private let queue = DispatchQueue(label: "com.contentful.formattercache") | ||
private var cache = [String: DateFormatter]() | ||
|
||
private init() {} | ||
|
||
func get(_ format: String, timeZone: TimeZone? = nil) -> DateFormatter { | ||
return queue.sync { | ||
if let formatter = cache[format] { | ||
return formatter | ||
} | ||
|
||
let formatter = DateFormatter() | ||
formatter.calendar = Calendar(identifier: .iso8601) | ||
// The locale and timezone properties must be exactly as follows to have a true, time-zone agnostic (i.e. offset of 00:00 from UTC) ISO stamp. | ||
formatter.locale = Foundation.Locale(identifier: "en_US_POSIX") | ||
formatter.timeZone = timeZone ?? TimeZone(secondsFromGMT: 0) | ||
formatter.dateFormat = format | ||
|
||
cache[format] = formatter | ||
|
||
return formatter | ||
} | ||
} | ||
} |