【问题标题】:Getting wrong time from dateformatter [duplicate]从 dateformatter 获取错误的时间 [重复]
【发布时间】:2017-03-22 13:54:34
【问题描述】:

我正在从 XML 文件转换日期字段,这些日期以“yyyyMMddHHmmss”格式存储。当我使用 DateFormmater 的日期函数时,我没有得到正确的时间。因此对于 dateString“20150909093700”,它返回“2015-09-09 13:37:00 UTC”而不是“2015-09-09 09:37:00”。在存储在 Core Data NSDate 字段中之前,我正在执行此转换。

这是我的代码:

static func stringToDate(DateString dateString: String) -> NSDate? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyyMMddHHmmss"
    dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(abbreviation: "EST")

    if let date = dateFormatter.date(from: dateString) {
        return date as NSDate?
    }

    return nil

}

【问题讨论】:

  • 您正在添加一个时区dateFormatter.timeZone = TimeZone(abbreviation: "EST") 计算日期时使用该时区的偏移量。只是一个 UTC 时区。
  • @rckoenes OP 的代码很好。他们只是误解了查看Date 值的输出。这已经在这里讨论了很多次了。
  • @rmaddy 第二次阅读,你可能是对的。

标签: ios swift3 nsdate


【解决方案1】:

@user30646 -- 看看这是否有意义。使用您的确切功能:

func stringToDate(DateString dateString: String) -> NSDate? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyyMMddHHmmss"
    dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(abbreviation: "EST")

    if let date = dateFormatter.date(from: dateString) {
        return date as NSDate?
    }

    return nil

}

let dateString = "20150909093700"

let returnedDate = stringToDate(DateString: dateString)

print("Date without formatting or Time Zone: [", returnedDate ?? "return was nil", "]")

let dFormatter = DateFormatter()
dFormatter.timeZone = TimeZone(abbreviation: "EST")
dFormatter.dateStyle = .full
dFormatter.timeStyle = .full

print("Result with formatting and Time Zone: [", dFormatter.string(from: returnedDate as! Date), "]")

你得到了“正确的时间”......你只是认为你不是因为你正在查看那个日期/时间的错误 字符串表示 .

【讨论】:

  • 这就解释了。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
相关资源
最近更新 更多