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

标签 swift date swift3 icalendar

我在 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 +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)

关于swift - 在 Swift 中创建特定时间的本地日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475168/

相关文章:

ios - 如何在 swift (IOS 8) 中连接蓝牙设备 (OBDII) 并发送/接收数据?

ios - Swift - 从字典中提取数据

ios - TableView 注册 - UINib 参数标签 '(nibName:, Bundle:)' 不匹配任何可用的重载

ios - TableView 循环遍历所有单元格以删除它们,Swift

postgresql - 在 Postgresql 中获取 ISO 日期的奇怪结果

Swift:如何显示明天的日期

php - 如何保存变量不显式的 PHP 字符串?

ios - 动画按钮从右边缩小宽度

arrays - Swift 3 升级错误--执行错误代码

ios - 动态调整 UITableView 的大小,它将显示为不可滚动的内容列表