将字符串转换为日期会中断本地时间

时间:2017-11-30 10:54:06

标签: swift date swift4

在我的例子中,我试图保存日志以测量今天和明天之间的日期。

因此,我将用户日期保存为旧日期。我的方法是:

1)将oldDate保存为Date() 2)转换并将时区添加为字符串 3)尝试转换回日期,这样我就可以用UTC时间记录日期。

在第3步中,我的UTC时间丢失了时间,我看到UTC 0时间。

代码和输出的屏幕截图如下:

Code Output

1 个答案:

答案 0 :(得分:1)

在此过程中没有任何东西丢失,一切都在那里。只是你理解print(date)不是根据你打印,而如果你打印一个日期对象,它将以UTC格式打印日期

见下面的例子

let oldDate = Date()
let dateFormat = DateFormatter()
dateFormat.dateFormat = "dd/MM/yy HH:mm"
dateFormat.calendar = Calendar.current
let oldDateFormattedString = dateFormat.string(from: oldDate)
print("Old date string: \(oldDateFormattedString)")
print("Old date: \(oldDate)")


let anotherDateFormat = DateFormatter()
anotherDateFormat.dateFormat = "dd/MM/yy HH:mm"
anotherDateFormat.calendar = Calendar.current
let anotherDate = anotherDateFormat.date(from: oldDateFormattedString)

print("Ano date: \(anotherDate!)")

<强>控制台

  

旧日期字符串:30/11/17 16:35
  旧日期:2017-11-30 11:05:47 +0000
  Ano日期:2017-11-30 11:05:00 +0000

您可以看到打印oldDateanotherDate时o / p几乎相同,除了您没有包含在日期格式字符串中的秒数。

e.g。在代码末尾添加这两行

let anotherDateString = anotherDateFormat.string(from: anotherDate!)
print("Ano date string: \(anotherDateString)")

您将看到控制台为

  

旧日期字符串:30/11/17 16:41
  旧日期:2017-11-30 11:11:51 +0000
  Ano日期:2017-11-30 11:11:00 +0000
  Ano日期字符串:30/11/17 16:41

相关问题