【问题标题】:Issue when converting a date string of format "yyyy-MM-dd HH:mm:ss.m" to "yyyy-MM-dd HH:mm:ss"将格式为“yyyy-MM-dd HH:mm:ss.m”的日期字符串转换为“yyyy-MM-dd HH:mm:ss”时出现问题
【发布时间】:2020-05-01 07:24:24
【问题描述】:

我正在 swift 5 中开发一个 iOS 项目。在我的一个 API 中,日期的格式为“yyyy-MM-dd HH:mm:ss.m”。从这个日期开始,我需要获取时间。但问题是,假设我从 API 获得的日期是“1900-01-01 08:30:00.000000”,当我将此日期格式转换为 YYYY-MM-dd HH:mm:ss 时,结果是以“1900-01-01 08:00:00”的形式出现,转换前的时间为 08:30:00.000000,但转换后的时间为 08:00:00。为什么会这样?请帮我。

我将在这里添加我的代码,

    let dateTime = "1900-01-01 08:30:00.000000"
    let outFormatter = DateFormatter()
    outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.m"

    if let date = outFormatter.date(from: dateTime) { 
        //here value od date is 1900-01-01 04:18:48 +0000
        outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        outFormatter.locale = tempLocale
        let exactDate = outFormatter.string(from: date)
        //here the value of exactDate is 1900-01-01 08:00:00
    }

【问题讨论】:

    标签: ios swift date-format dateformatter


    【解决方案1】:

    m 是分钟,S 是毫秒,所以格式必须是 "yyyy-MM-dd HH:mm:ss.S"

    对于固定日期格式,强烈建议将语言环境设置为en_US_POSIX

    let dateTime = "1900-01-01 08:30:00.000000"
    let outFormatter = DateFormatter()
    outFormatter.locale = Locale(identifier: "en_US_POSIX")
    outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.S"
    
    if let date = outFormatter.date(from: dateTime) {
        //here value od date is 1900-01-01 04:18:48 +0000
        outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    
        let exactDate = outFormatter.string(from: date)
        //here the value of exactDate is 1900-01-01 08:00:00
    }
    

    但是如果你只想从日期字符串中去掉毫秒,那么有一个更简单的解决方案

    let dateTime = "1900-01-01 08:30:00.000000"
    let exactDate = dateTime.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
    

    它会删除点和后面的任何数字

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      相关资源
      最近更新 更多