我有一个表视图,它有很少的单元格.我需要以人类可读的格式显示日期,其原始格式是从API调用中检索的.我正在使用下面的代码调用convertToDate函数,它负责获取格式为"yyyyyy—MM—dd'T 'HH:mm:ssX"的原始日期字符串,并将其转换为"MMMM dd,yyyyy'at 'hh:mm a".然而,正如我们所知,日期格式可能是昂贵的.有人可以帮助我回答一些问题看看下面的代码实现吗?

注意:我正在从tableView中的cellForRowAt方法调用函数convertToDate

  1. 创建一个Singleton类以便只创建一个DateFormatter实例(这样开销较低)是不是很好的做法?

  2. 我还创建了一个DispatchQueue,它是并发的,因此DateFormatter是线程安全的.这是很好的做法吗?

  3. 在滚动表视图时,使用并发的convertToDate调用convertToDate会导致性能延迟吗?

  4. 一般来说,是否有任何标准引用来处理/创建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
    }
}

推荐答案

  1. 不,扩展DateFormatter中的静态属性将是更好的 Select .
  2. 不需要Dateformatter

API调用返回最有可能的JSON.

在模型中定义表示日期的属性

let date: Date

并将.iso8601策略添加到解码器,以将ISO字符串即时转换为Date

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

在单元格格式中以现代方式显示日期

cell.date = item.date.formatted( Date.FormatStyle()
                     .year()
                     .month(.wide)
                     .day(.twoDigits)
                     .hour(.twoDigits(amPM: .abbreviated))
                     .minute()
                     .locale(.init(identifier: "en_US")))

风格也可以在外部定义.

Ios相关问答推荐

如何在react 本机模块中使用Bundle.main.Path()在SWIFT中导入assets资源

如何在SwiftUI中拥有基于操作系统版本的条件修饰符?

如何让3张组合的`SF Symbol`图片围绕一个特定点旋转?

如何使用 SwiftData 从列表中删除子项目?

如何删除点击时按钮的不透明动画?

如何链式设置 AttributeContainer 的 UIKit 属性?

更改图标会导致 SwiftUI 动画出现故障?

在 SwiftUI 中重构提取到子视图的 GeometryReader 代码

在 SwiftUI 中使用 .rotation3DEffect 在视图之间翻转

以正确的方式在 Text() 中使用 colored颜色

我们可以在 Swift 中将 struct 中的 Codable 键设置为不区分大小写吗

如何将标准化坐标系中的点的位置转换为具有相对位置的常规坐标系?

如何从 scendelegate 打开我的标签栏控制器

如何在 Swift 3 中根据 UIImage 的大小/比率调整 UIImageView 的大小?

有没有办法在 xib 文件中的视图和顶部布局指南之间添加约束?

使用 Chrome DevTools 调试 iOS 6+7 Mobile Safari

如何进行键值观察并在 UIView 的框架上获取 KVO 回调?

如何使用 presentModalViewController 创建透明视图

在 NSUserDefaults 中存储值是否有任何限制?

请在您的 Podfile 中为此目标指定一个平台?