【问题标题】:Convert from string to Date with current timezone使用当前时区从字符串转换为日期
【发布时间】:2019-11-19 16:25:31
【问题描述】:

我正在使用这些代码行将日期和时间转换为当前时区:

let calendar = Calendar(identifier: .gregorian)
let currentDate = Date()
let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:Z"
dateFormatter.timeZone = calendar.timeZone
dateFormatter.string(from:currentDate)

print(dateFormatter.string(from: currentDate))

print 输出给了我:

2019-11-19 17:22:55:+0100

我要将日期存储在 Realm 中,那么如何将其转换回 Date()

编辑;我尝试转换它,但它不起作用:

        let calendar = Calendar(identifier: .gregorian)
        let currentDate = Date()
        let dateFormatter = DateFormatter()

        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:Z"
        dateFormatter.timeZone = calendar.timeZone

        let dateString = dateFormatter.string(from:currentDate)
        let finalDate = dateFormatter.date(from: dateString)
        print(dateString) -> Gives me output: 2019-11-19 18:09:05:+0100 - This is the correct time!
        print(finalDate!) -> Gives me output: 2019-11-19 17:09:05 +0000

所以finalDate 应该将当前时间存储为Date(),但它没有得到正确的时间。

【问题讨论】:

  • 如果您的目标只是存储日期并转换回来,您应该使用 ISO8601 UTC 时间stackoverflow.com/questions/28016578/…
  • @LeoDabus 为什么会这样?
  • 您需要用户时区吗?否则只需使用 ISO8601。顺便说一句,如果您没有将日期格式化程序语言环境设置为 en_US_POSIX,您的解析可能会失败
  • 您检查了上面评论中的链接吗?顺便说一句,在向用户显示日期时,您可以使用 stackoverflow.com/questions/28332946/…
  • @LeoDabus 我正在创建一个锻炼日记应用,因此我想存储用户保存锻炼的日期和时间。

标签: ios swift xcode


【解决方案1】:

DateFormatter 也可以选择将字符串转换为日期:

let calendar = Calendar(identifier: .gregorian)
let currentDate = Date()
let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:Z"
dateFormatter.timeZone = calendar.timeZone
dateFormatter.date(from: yourStringDate)

【讨论】:

  • 我试过了,但是没用?请检查我的问题以获取更新。
【解决方案2】:

DateFormatter 双向转换。使用相同的格式化程序,将其转换回来,使用.date(from:)

let date = dateFormatter.date(from: string)

根据您的 cmets,您可能会误解 Date 是什么。日期只不过是自参考时间以来的秒数。它对时区一无所知。它对日历一无所知。它甚至对分钟或小时一无所知。它是只有从参考时间开始的几秒钟(它实际上是一个围绕单个 Double 值的小包装)。

当您打印 Date 时,它​​会调用 .description,并且作为程序员的便利,它由默认的 DateFormatter 生成,它将其转换为人类可读的字符串,纯粹用于调试目的。该字符串并不意味着 Date 附有日历或时区。这只是程序员的便利。它不应该被程序本身使用。

如果要处理时区,则必须使用 Calendar 来计算各种 DateComponents,或者使用 DateFormatter(使用 Calendar)来生成 String。

【讨论】:

  • 我试过了,但是没用?请检查我的问题以获取更新。
猜你喜欢
  • 1970-01-01
  • 2011-05-11
  • 2014-07-03
  • 2014-04-19
  • 2019-09-07
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 2017-07-29
相关资源
最近更新 更多