在 Swift 中的特定时间创建本地日期

Create a local date at a specific time in Swift

我在 Swift 中处理我的应用程序的当地时间日期时遇到问题。我想在午夜创建今天的日期,在 23:59 创建另一个实例。基本上有 2 个日期来覆盖当天的整个日期(想法是加载所有今天的日历条目)。我在操场上的代码:

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 在格林威治标准时间显示 Date 个实例。 2018-01-26 23:00:00 +00002018-01-27 00:00:00 +0100

是同一时间点

除此之外,我想建议一种更可靠的方法来使用 Calendar 强大的日期数学技能来获得 todayStartDatetodayEndDate

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)