【问题标题】:Create a local date at a specific time in Swift在 Swift 中的特定时间创建本地日期
【发布时间】:2018-01-27 11:12:33
【问题描述】:

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

我最终有时间在那里:

“2018 年 1 月 27 日凌晨 12:00”

打印输出:

“2018-01-26 23:00:00 +0000\n”

【问题讨论】:

  • 一切都是正确的。打印 Date 始终使用 GMT 时区,例如比较stackoverflow.com/questions/39937019/…。 – 所以“2018-01-26 23:00:00 +0000”是您所在时区的 2018-01-27 午夜。

标签: swift date swift3 icalendar


【解决方案1】:

答案——正如 cmets 中已经提到的——是: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)

【讨论】:

  • 非常感谢,这很有意义。我唯一想知道的是 todayStartDate 给出了实际时间,如果我的日历条目发生得更早,它可能不会加载。
  • todayStartDate 被声明为 inout 指针,初始值无关紧要。代表今天午夜的实际日期将在dateInterval(of: 行中设置。日期的时间部分设置为零,除非在当地时区今天没有0:00:00,例如在巴西秋季夏令时更改时。在这种情况下,时间设置为日期的实际第一秒。
猜你喜欢
  • 1970-01-01
  • 2020-04-28
  • 2018-10-03
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多