【问题标题】:Get Local time zone date by date component按日期组件获取本地时区日期
【发布时间】:2017-04-02 17:59:39
【问题描述】:

好的,这是我将当前日期格式化为 GMT 格式并以日期类型返回值的代码。我在调试时'po' nowComponent 变量,它显示了当前的本地时区值,但代码块'calendar.date(来自:nowComponents)!'仍然给我一个UTC日期。如何获取本地时区的日期?

    var nowComponents = DateComponents()
    let date = Date()

    nowComponents.year = (calendar as NSCalendar).component(NSCalendar.Unit.year, from: date)
    nowComponents.month = (calendar as NSCalendar).component(NSCalendar.Unit.month, from: date)
    nowComponents.day = (calendar as NSCalendar).component(NSCalendar.Unit.day, from: date)
    nowComponents.hour = (calendar as NSCalendar).component(NSCalendar.Unit.hour, from: date)
    nowComponents.minute = (calendar as NSCalendar).component(NSCalendar.Unit.minute, from: date)
    nowComponents.second = (calendar as NSCalendar).component(NSCalendar.Unit.second, from: date)

    (nowComponents as NSDateComponents).timeZone = TimeZone.current

    return calendar.date(from: nowComponents)!

【问题讨论】:

  • 我使用 dateFormatter 将日期转换为本地时区,并且成功了!但我喜欢使用 calendar.current 或 calendar.date 来实现日期转换。

标签: ios swift date


【解决方案1】:

您的任何代码都不是必需的。行:

let date = Date()

就是你所需要的。这将为您提供当前日期和时间。

您的错误是使用po 打印日期。这在日期上使用description 方法,该方法显示日期的调试输出,并且该输出以UTC 时间显示日期。

如果您想以字符串形式查看本地时间的日期,请使用DateFormatter

let df = DateFormatter()
df.dateStyle = .long
df.timeStyle = .long
let str = df.string(from: date)
print(str)

这将显示当地时间的日期。

【讨论】:

  • 谢谢。正如我提到的 dateFormatter 工作但它将日期格式化为字符串。实际上我喜欢获取日期类型的值。再次将“str”转换为日期对象?
  • 没有必要。日期就是日期。它没有格式。
  • 也许我误解了日期转换。我认为日期对象可以是 UTC(默认)格式和 GMT 格式。根据您的解释,日期类型对象始终以 UTC 显示,对吗?如果我想获得 GMT 日期值,那么我需要做 DateFormatter。因为我尝试将“小时”添加到将值从“2017 年 4 月 3 日晚上 11:50”(格林威治标准时间)更改为“2017 年 4 月 4 日凌晨 2:50”(格林威治标准时间)的日期,但是当我读取日期变量以进行进一步处理时它返回“2017 年 4 月 3 日”日期,因为它是 UTC 格式。我预计日期是“2017 年 4 月 4 日”......
  • A Date 在使用 DateFormatter 转换为 String 之前没有显示。当您记录日期时,这就是实际发生的情况。日期将转换为字符串,并且该字符串仅在 UTC 时区中显示。您无需进行任何转换或更改。
猜你喜欢
  • 2014-02-22
  • 2011-08-12
  • 2017-12-15
  • 1970-01-01
  • 2021-01-16
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 2016-12-26
相关资源
最近更新 更多