[英]How to print Date&time (localized) in current timezone using SwiftDate framework
I'm using SwiftDate framework (see link below) https://github.com/malcommac/SwiftDate我正在使用 SwiftDate 框架(见下面的链接) https://github.com/malcommac/SwiftDate
I'd like to print the date and time in current region/local/timeZone.我想打印当前地区/本地/时区的日期和时间。 I can achieve this by using the below code without using SwiftDate:
我可以通过使用以下代码而不使用 SwiftDate 来实现这一点:
DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short)
Since, SwiftDate provides a shared date formatter.因为,SwiftDate 提供了一个共享的日期格式化程序。 I'd like to know if the same is possible with SwiftDate.
我想知道 SwiftDate 是否也可以这样做。
I use an extension to get localized date:我使用扩展来获取本地化日期:
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))
}
}
Then you use it like this (if you need system localized date, just ommit extension part):然后你像这样使用它(如果你需要系统本地化日期,只需省略扩展部分):
let dateString = Date().localizedDate.toString(.custom("dd.MM.yyyy."))
I tried predrag-samardzic code and it worked.我尝试了 predrag-samardzic 代码并且它起作用了。 Now that there are two options (to do the same job), one with NSDateFormatter and the other with SwiftDate, I thought of profiling them to see which one is better.
现在有两种选择(做同样的工作),一种使用 NSDateFormatter,另一种使用 SwiftDate,我想对它们进行分析以查看哪个更好。 Here's the code that I used to profile them:
这是我用来分析它们的代码:
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))
}
}
Here's the screenshot from the profiler.这是分析器的屏幕截图。
The result of profiling:分析结果:
NSDateFormatter - 773x SwiftDate - 2674x NSDateFormatter - 773x SwiftDate - 2674x
NSDateFormatter is approximately 3.45 times faster than SwiftDate. NSDateFormatter 大约比 SwiftDate 快 3.45 倍。 Based on the above, I'd recommend using NSDateFormatter over SwiftDate.
基于上述,我建议在 SwiftDate 上使用 NSDateFormatter。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.