Swift 4.1和#x27;t不将字符串转换为本地日期,始终返回UTC日期
我想将日期字符串转换为日期Swift 4.1和#x27;t不将字符串转换为本地日期,始终返回UTC日期,swift,date,localtime,Swift,Date,Localtime,我想将日期字符串转换为日期 let a = DateFormatter() a.dateFormat = "yyyy-MM-dd HH:mm:ss" guard let datea = a.date(from: "2018-06-21 00:00:00") else { fatalError("ERROR: Date conversion failed due to mismatched format.") } print("ans", datea) 但它总是打印“ans 20
let a = DateFormatter()
a.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let datea = a.date(from: "2018-06-21 00:00:00") else {
fatalError("ERROR: Date conversion failed due to mismatched format.")
}
print("ans", datea)
但它总是打印“ans 2018-06-20 16:00:00+0000”
为什么不能打印原始字符串日期“2018-06-21 00:00:00”?
我的代码怎么了?日期不是字符串。约会是一个时间的瞬间。它没有钟。它没有时区。它没有日历。它只是一个瞬间,与位置或定位无关 为了便于调试,可以使用日期的
.description
(这就是print
调用的内容)轻松地将日期转换为预定义格式的字符串。与所有.description
方法一样,除了调试(或可能的日志记录)之外,您不应该将此字符串用于任何事情。关于这个字符串的格式没有任何保证
如果需要某些特定的字符串表示,则应使用DateFormatter
:
print("ans", a.string(from: datea))
您需要提供
时区
以根据提供的时区获取时间,以便将UTC时间转换为本地时间,您的代码应该是这样的
let a = DateFormatter()
a.dateFormat = "yyyy-MM-dd HH:mm:ss"
a.timeZone = TimeZone(abbreviation: "UTC")
let dt = a.date(from: "2018-06-21 00:00:00")
a.timeZone = TimeZone.current
a.dateFormat = "yyyy-MM-dd HH:mm:ss" //change the dateFormat according to your need
let dateString = a.string(from: dt!)
print("now the dateString is \(dateString)")
//printed result (now the dateString is 2018-06-21 05:30:00 )
正如Rob Napier在回答中所说,
Date
对象没有时区。它代表了地球上任何地方的一个时刻
如果要将日期显示为月、日、年和时间,则需要指定特定时区
如果您只打印一个日期,如print(date())
,则会得到日期对象的默认description
属性,该属性显示以UTC表示的日期。那可能不是你想要的
我定义了一个日期扩展,它允许我查看以用户当前语言环境和时区表示的日期:
extension Date {
func localString(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String {
return DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle)
}
func timeString(timeStyle: DateFormatter.Style = .medium) -> String {
return localString(dateStyle: .none, timeStyle: timeStyle)
}
}
如果将该扩展添加到项目中,则可以如下方式使用它:
print(print("ans", datea.localString())
您将在设备的当前时区中看到您的日期。这对于调试非常有用。因为
print
根据定义总是以UTC显示日期。如果需要本地时间,请使用另一个日期格式化程序,或将输入格式化程序的时区设置为UTCadda.timeZone=timeZone(缩写:“GMT+0:00”)
//当前时区