如何用Swift中人类可读的日期替换字符串中的日期?



我从服务器得到一个字符串,它看起来像:

You blocked until 2022-01-01T11:00:00.350Z

现在我想把它转换成人类可读的日期,比如

2022-01-01 11:00

对于这个,我试着先找到日期:

let types: NSTextCheckingResult.CheckingType = [.date]
if let detector = try? NSDataDetector(types: types.rawValue) {
let range = NSMakeRange(0, message.count)
let matches = detector.matches(in: message, 
options: NSRegularExpression.MatchingOptions(rawValue: 0), 
range: range)
if !matches.isEmpty {
for match in matches {
print(match.date)
let aSubstring = NSString(string: message).substring(with: match.range)
print(aSubstring)
}
}
}

因此,match.date返回给我2022-01-01 11:00:00 +0000,而aSubstring的结果是until 2021-08-02T11:38:10.214Z。所以我很好奇为什么它包括until到子字符串,我怎么能避免?

一种可能的解决方案是使用正则表达式提取ISO8601字符串省略秒,小数秒和时区,然后获得前10个字符(日期)和最后5个字符(时间)

let string = "You blocked until 2022-01-01T11:00:00.350Z"
if let range = string.range(of: "\d{4}-\d{2}-\d{2}T\d{2}:\d{2}", options: .regularExpression) {
let trimmedString = String(string[range])
let humanReadable = "(trimmedString.prefix(10)) (trimmedString.suffix(5))"
print(humanReadable) // 2022-01-01 11:00
}

然而,有一个警告:日期是在UTC。如果希望日期显示在当前时区,则必须使用日期格式化程序(实际上是两个)

let string = "You blocked until 2022-01-01T11:00:00.350Z"
if let range = string.range(of: "\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}", options: .regularExpression) {
let trimmedString = String(string[range]) + "Z"
let inputFormatter = ISO8601DateFormatter()
if let date = inputFormatter.date(from: trimmedString) {
let outputFormatter = DateFormatter()
outputFormatter.locale = Locale(identifier: "en_US")
outputFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let humanReadable = outputFormatter.string(from: date)
print(humanReadable)
}
}

如果日期部分位于字符串的末尾,则你可以尝试一些更复杂但可行的方法。像这样:

struct ContentView: View {
@State var txt = ""
func humanDate(_ str: String) -> String? {
// convert the string to a date
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
// re-format the date to your liking
if let date = dateFormatter1.date(from: str) {
let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm"
// dateFormatter2.dateFormat = "yyyy MMMM EEEE HHa:mm" // even more human readable                
return dateFormatter2.string(from: date)
} else {
return nil
}
}

var body: some View {
Text(txt).onAppear {

let inputString = "You blocked until 2022-01-01T11:00:00.350Z"
if let dateStr = inputString.split(separator: " ").last {
if let theDate = humanDate(String(dateStr)) {
print("n----> " + theDate + "n")
txt = theDate
}
}

}
}
}

相关内容

  • 没有找到相关文章

最新更新