【问题标题】:How to convert string to date without time in Swift 3?如何在 Swift 3 中将字符串转换为没有时间的日期?
【发布时间】:2017-07-16 19:03:33
【问题描述】:

我尝试将日期(如 2017-02-11 字符串)转换为日期,但结果返回给我类似 2017-02-10 16:00:00 +0000 的内容。我正在使用下面的代码。

let localDate = dateFormatter.string(from: date) //2017-02-11

    let dateFormatter2 = DateFormatter()
    dateFormatter2.dateFormat = "yyyy-MM-dd"

    let selectedDate = dateFormatter2.date(from: localDate)
    print("Did Select \(selectedDate)") // 2017-02-10 16:00:00 +0000

【问题讨论】:

  • 你可以显示日期而不显示时间但是没有没有时间的日期
  • 日期正确。 print 以 UTC 显示日期,您的本地时区显然是 UTC+8

标签: swift string date time format


【解决方案1】:
let dateWithTime = Date()

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short

let date = dateFormatter.string(from: dateWithTime) // 2/10/17

这将正确格式化它,但这仅用于显示目的。所有Dates 都有时间。

【讨论】:

    【解决方案2】:

    确实没有没有时间元素的Date,但是如果您需要一些可以用来比较整天的东西,您可以使用给定Date 的第一时刻

    Calendar.current.startOfDay(for: dateWithTime)
    

    【讨论】:

      猜你喜欢
      • 2017-09-16
      • 2018-03-30
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多