我在 Swift 中处理应用程序的本地时间日期时遇到问题。我想在午夜创建今天的日期,并在 23:59 创建另一个实例。基本上是 2 个日期来覆盖当天的所有内容(想法是加载今天的所有日历条目)。我在 Playground 上的代码:
import Foundation
let dateFormatter = DateFormatter()
let date = Date()
dateFormatter.dateFormat = "yyyy-MM-dd"
let todayStartDate = dateFormatter.date(from: dateFormatter.string(from: date))
let todayEndDate = dateFormatter.date(from: dateFormatter.string(from: Calendar.current.date(byAdding: .day, value: 1, to: date)!))
print(todayStartDate!)
print(todayEndDate!)
我最终在那里度过了时间:
"Jan 27, 2018 at 12:00 AM"
打印输出:
"2018-01-26 23:00:00 +0000\n"
最佳答案
答案 - 正如评论中已经提到的 - 是:print
显示 GMT 中的 Date
实例。 2018-01-26 23:00:00 +0000
与 2018-01-27 00:00:00 +0100
除此之外,我还想建议一种更可靠的方法,使用 Calendar
强大的日期数学来获取 todayStartDate
和 todayEndDate
技能。
let calendar = Calendar.current
var todayStartDate = Date()
var interval = TimeInterval()
calendar.dateInterval(of: .day, start: &todayStartDate, interval: &interval, for: Date())
let todayEndDate = calendar.date(byAdding: .second, value: Int(interval-1), to: todayStartDate)!
print(todayStartDate)
print(todayEndDate)
关于swift - 在 Swift 中创建特定时间的本地日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475168/