【问题标题】:How to make NSDate() print the current local time [duplicate]如何使 NSDate() 打印当前本地时间 [重复]
【发布时间】:2016-04-03 06:36:43
【问题描述】:

我在游乐场尝试过这个(我在 cmets 中显示了它的打印内容):

extension NSDate {

    static func currentDate() -> NSDate {
        let calendar = NSCalendar.currentCalendar()
        calendar.timeZone = NSTimeZone.localTimeZone()
        calendar.locale = NSLocale.currentLocale()

        let components = calendar.components([.Year, .Month, .Day], fromDate: NSDate())
        components.hour = 00
        components.minute = 00
        components.second = 00

        return calendar.dateFromComponents(components)! // "Dec 29, 2015, 12:00 AM"
    }
}

print(NSDate.currentDate()) // "2015-12-28 22:00:00 +0000

有人知道这里发生了什么吗?

我只想要当前日期(年/月/日)。我做了这个扩展,因为我遇到了NSDate() 的问题,它关闭了 2 小时(显示上午 11.24,而不是下午 1.24)

【问题讨论】:

  • 您可以随时使用带有语言环境的描述来打印不同的时间stackoverflow.com/a/28405039/2303865
  • 这个想法是我将一些对象添加到 tableView 中,其中还包含一个 NSDate 属性。当日期发生变化时,假设是上午 12.05,并且我添加了一个元素,我希望当前日期为 30,但使用当前代码,它仍然有日期第 29 天,因为它有 2 小时的休息时间。我不只是想正确打印它。
  • @Adrian:NSDate 是一个绝对时间点(内部存储为自格林威治标准时间 2001 年 1 月 1 日以来的秒数),并且对您的时区等一无所知。解释一个NSDate 根据您的时区,您必须使用 NSCalendar 和 NSDateComponents,或者使用 NSDateFormatter 将其转换为字符串。
  • @MartinR:这就是我试图在我的代码中使用的。 currentTimezone 和 currentLocale。不确定它是否正确。
  • @Adrian:但是您正在将日期组件转换回 NSDate,并且打印 NSDate 使用它的描述方法,并且使用 UTC 的默认格式打印时间。

标签: ios swift nsdate


【解决方案1】:

Swift 中的 NSDate() 和 Objective-C 中的 [NSDate date] 都包含 UTC 日期。你不能改变它的行为。

但是,您可以创建格式化程序并转换为所需的语言环境和日期格式,并将日期存储为字符串值。

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /*your desired format*/
let date = dateFormatter.dateFromString(/*your date string*/)

【讨论】:

  • 但是如果我在上午 12 点 30 分向表格视图添加一些具有 NSDate 属性的元素,由于我的问题,日期仍然是 12 月 29 日而不是 12 月 30 日。
猜你喜欢
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 2016-09-03
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
相关资源
最近更新 更多