在 Swift 中解析 Javascript new Date().toString()

问题描述

我需要快速解析 javascript 日期。由于日期已经存储在某个数据库中,我无法更改它们的格式。我只需要快速将它们解析为正确的日期。

以下是 javascript 的 toString() 函数的示例结果。这取决于区域设置/语言

// js
new Date().toString()
'Tue Jun 01 2021 14:11:27 GMT+0900 (JST)'
'Tue Jun 01 2021 14:03:45 GMT+0900 (Japan Standard Time)'
'Mon May 31 2021 17:38:31 GMT+0800 (中国標準時)'
'Mon May 31 2021 19:25:37 GMT+0930 (オーストラリア中部標準時)'

如何在 Swift DateFormatter 中解析它?

我已经试过了:

// swift
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z (zzz)"

Date-> String 转换看起来正确但 String -> Date 不起作用

// swift
dateFormatter.string(from: Date())
> "Tue Jun 01 2021 14:11:27 GMT+0900 (JST)"
dateFormatter.date(from: "Tue Jun 01 2021 14:11:27 GMT+0900 (JST)")
> nil

非常感谢任何帮助。

解决方法

正如@Sweeper 在评论中提到的 - 时区名称部分取决于实现 - 可以从 docs

确认
Optionally,a timezone name consisting of:
space
Left bracket,i.e. "("
An implementation dependent string representation of the timezone,which might be an abbreviation or full name (there is no standard for names or abbreviations of timezones),e.g. "Line Islands Time" or "LINT"
Right bracket,i.e. ")"

所以我们需要 - 删除最后括号内的部分并解析其余部分 - 正如@Joakim Danielson 所提到的

考虑到这一点,我们可以这样做 -

extension String {
    
    static private var jsDateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z"
        return formatter
    }()
    
    func parsedDate() -> Date? {
        let input = self.replacingOccurrences(of: #"\(.*\)$"#,with: "",options: .regularExpression)
        return String.jsDateFormatter.date(from: input)
    }
    
}

测试

func testJSDateParsing() {
    [
        "Tue Jun 01 2021 14:11:27 GMT+0900 (JST)","Tue Jun 01 2021 14:03:45 GMT+0900 (Japan Standard Time)","Mon May 31 2021 17:38:31 GMT+0800 (中国標準時)","Mon May 31 2021 19:25:37 GMT+0930 (オーストラリア中部標準時)",].forEach({
        if let date = $0.parsedDate() {
            print("Parsed Date : \(date) for input : \($0)")
        }
        else {
            print("Failed to parse date for : \($0)")
        }
    })
}

输出

Parsed Date : 2021-06-01 05:11:27 +0000 for input : Tue Jun 01 2021 14:11:27 GMT+0900 (JST)
Parsed Date : 2021-06-01 05:03:45 +0000 for input : Tue Jun 01 2021 14:03:45 GMT+0900 (Japan Standard Time)
Parsed Date : 2021-05-31 09:38:31 +0000 for input : Mon May 31 2021 17:38:31 GMT+0800 (中国標準時)
Parsed Date : 2021-05-31 09:55:37 +0000 for input : Mon May 31 2021 19:25:37 GMT+0930 (オーストラリア中部標準時)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...