gpt4 book ai didi

swift - NSDate() 或 Date() 显示错误的时间

转载 作者:行者123 更新时间:2023-11-30 10:38:56 24 4
gpt4 key购买 nike

当我尝试记录当前日期时:

print(NSDate())

print(Date()) 

(在 Swift 3 中)

或者任何日期对象,它显示错误的时间。比如现在大概是16点12分,但是上面显示的是

2016-10-08 20:11:40 +0000

我的约会时区是否错误?如何修正我的日期以获得正确的时区?

为什么会这样,如何解决?如何在打印语句或调试器中轻松显示本地时区的任意日期?

(请注意,这个问题是一个“铃声”,以便我可以提供一个简单的 Swift 3/Swift 2 Date/NSDate 扩展,让您轻松显示本地时区的任何日期对象。

最佳答案

NSDate(或 Swift ≥ V3 中的日期)没有时区。它记录了世界各地的时间瞬间。

在内部,日期对象记录自“纪元日期”以来的秒数,或 2001 年 1 月 1 日午夜 Greenwich Mean Time 中的秒数。 ,又名 UTC。

我们通常会考虑本地时区的日期。

如果您使用记录日期

print(NSDate()) 

系统显示当前日期,但以 UTC/格林威治标准时间表示。因此,时间看起来正确的唯一地方就是该时区。

如果您发出调试器命令,您会在调试器中遇到相同的问题

e NSDate()

这是一个痛苦。我个人希望 iOS/Mac OS 能够使用用户当前时区显示日期,但事实并非如此。

编辑#2:

对我之前使用本地化字符串的改进是创建 Date 类的扩展,使其更易于使用:

extension Date {
func localString(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String {
return DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle)
}
}

这样你就可以使用像 Date().localString() 这样的表达式,或者如果你只想打印时间,你可以使用 Date().localString(dateStyle :.无)

编辑:

我刚刚发现NSDateFormatter(Swift 3中的DateFormatter)有一个类方法localizedString。这与我下面的扩展的作用相同,但更简单、更干净。以下是声明:

class func localizedString(from date: Date, dateStyle dstyle: DateFormatter.Style, timeStyle tstyle: DateFormatter.Style) -> String

所以你只需使用

let now = Date()
print (DateFormatter.localizedString(
from: now,
dateStyle: .short,
timeStyle: .short))

您几乎可以忽略下面的所有内容。

<小时/>

我创建了 NSDate 类的一个类别(Swift 3 中的 Date),它有一个 localDateString 方法,可以显示用户本地时区的日期。

这是 Swift 3 形式的类别:(文件名 Date_displayString.swift)

extension Date {
@nonobjc static var localFormatter: DateFormatter = {
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateStyle = .medium
dateStringFormatter.timeStyle = .medium
return dateStringFormatter
}()

func localDateString() -> String
{
return Date.localFormatter.string(from: self)
}
}

以 Swift 2 形式:

extension NSDate {
@nonobjc static var localFormatter: NSDateFormatter = {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateStyle = .MediumStyle
dateStringFormatter.timeStyle = .MediumStyle
return dateStringFormatter
}()

public func localDateString() -> String
{
return NSDate.localFormatter.stringFromDate(self)
}
}

(如果您喜欢不同的日期格式,可以很容易地修改日期格式化程序使用的格式。也可以直接显示您需要的任何时区的日期和时间。)

我建议将此文件的相应 Swift 2/Swift 3 版本放入您的所有项目中。

然后您可以使用

swift 2:

print(NSDate().localDateString())

swift 3:

print(Date().localDateString())

关于swift - NSDate() 或 Date() 显示错误的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57280201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com