我有一个表视图,它有很少的单元格.我需要以人类可读的格式显示日期,其原始格式是从API调用中检索的.我正在使用下面的代码调用convertToDate函数,它负责获取格式为"yyyyyy—MM—dd'T 'HH:mm:ssX"的原始日期字符串,并将其转换为"MMMM dd,yyyyy'at 'hh:mm a".然而,正如我们所知,日期格式可能是昂贵的.有人可以帮助我回答一些问题看看下面的代码实现吗?
注意:我正在从tableView中的cellForRowAt方法调用函数convertToDate
-
创建一个Singleton类以便只创建一个DateFormatter实例(这样开销较低)是不是很好的做法?
-
我还创建了一个DispatchQueue,它是并发的,因此DateFormatter是线程安全的.这是很好的做法吗?
-
在滚动表视图时,使用并发的convertToDate调用convertToDate会导致性能延迟吗?
-
一般来说,是否有任何标准引用来处理/创建Dateformatter?
以下代码将"2023-12-22T13:17:27Z"转换为"2023年12月22日下午01:17"
代码
import Foundation
class DateUtils {
static let shared = DateUtils()
let dateFormatter = DateFormatter()
// Date formatter are not thread safe and adding this to a concurrent queue makes if safer.
// For table views cells this may have minimal impact and needs to have performance tested in different cases where used.
private let dateFormatterQueue = DispatchQueue(label: "com.example.dateformatter",
attributes: .concurrent)
private init(){}
func convertToDate(from date: String,
with format: String = "yyyy-MM-dd'T'HH:mm:ssX",
to: String = "MMMM dd, yyyy 'at' hh:mm a") -> String? {
var formattedDate: String?
dateFormatter.dateFormat = format
guard let date = dateFormatter.date(from: date) else {
return nil
}
dateFormatter.dateFormat = to
dateFormatterQueue.sync {
formattedDate = dateFormatter.string(from: date)
}
return formattedDate
}
}