【问题标题】:Swift date string to Date fails when milliseconds has fractional value (value other than 000)当毫秒具有小数值(000 以外的值)时,Swift 日期字符串到日期失败
【发布时间】:2019-12-16 11:28:13
【问题描述】:

我这里有一些奇怪的情况

我正在尝试将我的 dateString 转换为 Date,只要我的日期有小数毫秒(值超过 000),它就会失败

2019-12-16T10:23:47.000Z  // works fine 


2019-12-16T10:23:47.673Z // fails

这是我的字符串扩展

extension String {
    func getFormattedDate() -> String {
        let dateFormatterGet = DateFormatter()
        // "2019-12-16T10:23:47.000Z"
        dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sssZ" 

        let dateFormatterPrint = DateFormatter()
        dateFormatterPrint.dateFormat = "dd-MM-yy" 


        let date: Date? = dateFormatterGet.date(from: self) 
        // here date value returns nil when i have fractional milliseconds

        print("Date",dateFormatterPrint.string(from: date!)) // prints 16-12-19


        //it fails in below line saying "Fatal error: Unexpectedly found nil while unwrapping 
        // an Optional value" as date returns nil
        return dateFormatterPrint.string(from: date!); 
    }
   }

提前致谢

【问题讨论】:

  • 使用SSS 表示小数秒,而不是sss

标签: swift date dateformatter


【解决方案1】:

毫秒的格式说明符是SSS,但是你使用了sss,导致解析失败。

您可以使用正确的格式解决此问题:

dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

或者,由于格式是 ISO 8601,您可以使用ISO8601DateFormatter

let dateFormatterGet = ISO8601DateFormatter()
// you only need the date, so only withFullDate
dateFormatterGet.formatOptions = [.withFullDate] 
// if you need to parse everything, you need the following options:
// [.withFullDate, .withFullTime, .withFractionalSeconds, .withTimeZone]

【讨论】:

    【解决方案2】:

    你需要

    dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 
    

    【讨论】:

      猜你喜欢
      • 2018-12-22
      • 2014-10-12
      • 2022-06-13
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 2017-03-01
      相关资源
      最近更新 更多