You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Swift 4.1获取URL参数中的日期(不含时间)

如何从URL查询参数中提取日期部分而非完整日期时间?

看起来你已经有了获取URL查询参数的基础代码,现在只需要对拿到的完整日期时间字符串做进一步处理,就能提取出纯日期部分。这里给你两种实用的解决方案,按需选择:

方案一:直接字符串分割(简单高效)

如果你的查询参数里的日期时间格式固定是yyyy-MM-dd HH:mm(也就是日期和时间用空格分隔),直接按空格分割取第一部分就行,代码修改如下:

extension URL {
    // 新增专门提取日期部分的方法
    func dateValueOf(_ queryParameterName: String) -> String? {
        guard let urlComponents = URLComponents(string: self.absoluteString),
              // 这里用lowercased()匹配,避免大小写敏感的问题(比如参数是FromDate你写成fromDate)
              let fullDateTime = urlComponents.queryItems?.first(where: { $0.name.lowercased() == queryParameterName.lowercased() })?.value else {
            return nil
        }
        // 按空格分割字符串,取第一部分就是日期
        return fullDateTime.components(separatedBy: " ").first
    }
}

// 注意:原代码里URL初始化缺少http://,会导致解析失败,一定要补上
guard let newURL = URL(string: "http://assetlinkasia.no-ip.biz:8001/hf_tracker/api/history.php?accesskey=12345&Vehilce=1618&FromDate=2018-05-10 13:11&ToDate=2018-05-14 12:11") else {
    fatalError("Invalid URL format")
}

// 使用示例
if let fromDate = newURL.dateValueOf("FromDate") {
    print("提取的起始日期:\(fromDate)") // 输出:2018-05-10
}

if let toDate = newURL.dateValueOf("ToDate") {
    print("提取的结束日期:\(toDate)") // 输出:2018-05-14
}

方案二:用DateFormatter解析(更健壮)

如果担心后续日期时间格式可能变化,或者需要验证输入的有效性,推荐用DateFormatter先解析成Date对象,再格式化为纯日期字符串:

extension URL {
    func formattedDateValueOf(_ queryParameterName: String) -> String? {
        guard let urlComponents = URLComponents(string: self.absoluteString),
              let fullDateTime = urlComponents.queryItems?.first(where: { $0.name.lowercased() == queryParameterName.lowercased() })?.value else {
            return nil
        }
        
        // 定义输入的日期时间格式
        let inputFormatter = DateFormatter()
        inputFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        inputFormatter.locale = Locale(identifier: "en_US_POSIX") // 避免区域设置影响解析
        
        // 解析成Date对象,失败则返回nil
        guard let date = inputFormatter.date(from: fullDateTime) else {
            print("日期时间格式无效:\(fullDateTime)")
            return nil
        }
        
        // 定义输出的纯日期格式
        let outputFormatter = DateFormatter()
        outputFormatter.dateFormat = "yyyy-MM-dd"
        return outputFormatter.string(from: date)
    }
}

// 使用示例
guard let newURL = URL(string: "http://assetlinkasia.no-ip.biz:8001/hf_tracker/api/history.php?accesskey=12345&Vehilce=1618&FromDate=2018-05-10 13:11&ToDate=2018-05-14 12:11") else {
    fatalError("Invalid URL format")
}

if let fromDate = newURL.formattedDateValueOf("FromDate") {
    print("起始日期:\(fromDate)")
}

if let toDate = newURL.formattedDateValueOf("ToDate") {
    print("结束日期:\(toDate)")
}

额外提醒

  • 原代码里的URL初始化缺少http://,这会导致URLComponents无法正确解析,一定要补上协议头;
  • 如果你的查询参数名大小写是固定的(比如就是FromDate和ToDate),可以去掉lowercased()匹配,提升一点性能;
  • 方案一适合格式完全固定的场景,代码更简洁;方案二更灵活,能处理格式验证和后续的格式调整。

内容的提问来源于stack exchange,提问作者Rehan Meo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:10:00