簡體   English   中英

如何使用 SwiftDate 框架在當前時區打印日期和時間(本地化)

[英]How to print Date&time (localized) in current timezone using SwiftDate framework

我正在使用 SwiftDate 框架(見下面的鏈接) https://github.com/malcommac/SwiftDate

我想打印當前地區/本地/時區的日期和時間。 我可以通過使用以下代碼而不使用 SwiftDate 來實現這一點:

DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short)

因為,SwiftDate 提供了一個共享的日期格式化程序。 我想知道 SwiftDate 是否也可以這樣做。

我使用擴展來獲取本地化日期:

import SwiftDate

extension Date {

//you can specify region/timezone/locale to what you want
    var localizedDate: DateInRegion {
        return self.in(region: Region(calendar: Calendar.current, zone: Zones.current, locale: Locale.current))
    }
}

然后你像這樣使用它(如果你需要系統本地化日期,只需省略擴展部分):

let dateString = Date().localizedDate.toString(.custom("dd.MM.yyyy."))

我嘗試了 predrag-samardzic 代碼並且它起作用了。 現在有兩種選擇(做同樣的工作),一種使用 NSDateFormatter,另一種使用 SwiftDate,我想對它們進行分析以查看哪個更好。 這是我用來分析它們的代碼:

func testNSDateFormatter() {
    for _ in 1...10000 {
        print("\(Date().toLocalizedString())")
    }
}

func testSwiftDate() {
    for _ in 1...10000 {
        print("\(Date().localizedDate.toString(.dateTime(.short)))")
    }
}

extension Date {
    func toLocalizedString(dateStyle: DateFormatter.Style = .short, timeStyle: DateFormatter.Style = .short) -> String {
        return DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle)
    }

    var localizedDate: DateInRegion {
         return self.in(region: Region(calendar: Calendar.current, zone: Zones.current, locale: Locale.current))
    }
}

這是分析器的屏幕截圖。

NSDateFormatter 與 SwiftDate - 時間配置文件

分析結果:

NSDateFormatter - 773x SwiftDate - 2674x

NSDateFormatter 大約比 SwiftDate 快 3.45 倍。 基於上述,我建議在 SwiftDate 上使用 NSDateFormatter。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM