如何在swift 4中获得今天和明天的约会

Ami*_*Pal -3 time ios swift swift4

如何获取当前日期unix-epoch? timeIntervalSince1970打印当前时间.上午12点有什么方法可以获得今天的时间吗?

例如,当前时间是:2018年1月7日下午5:30.timeIntervalSince1970将打印当前时间即1546903800000.时代系统中的当前日期将是2018年1月7日00:00 AM.即1546848000000

Man*_*ish 12

使用此扩展获取今天和明天的日期

extension Date {
   static var tomorrow:  Date { return Date().dayAfter }
   static var today: Date {return Date()}
   var dayAfter: Date {
      return Calendar.current.date(byAdding: .day, value: 1, to: Date())!
   }
}
Run Code Online (Sandbox Code Playgroud)


rma*_*ddy 6

这可以使用以下代码非常简单地完成.无需日期组件或其他并发症.

var calendar = Calendar.current
// Use the following line if you want midnight UTC instead of local time
//calendar.timeZone = TimeZone(secondsFromGMT: 0)
let today = Date()
let midnight = calendar.startOfDay(for: today)
let tomorrow = calendar.date(byAdding: .day, value: 1, to: midnight)!

let midnightEpoch = midnight.timeIntervalSince1970
let tomorrowEpoch = tomorrow.timeIntervalSince1970
Run Code Online (Sandbox Code Playgroud)


Jef*_*mas 5

我会用组件来做到这一点。

假设您需要按秒定义的时间time(2)。如果您需要以定义的毫秒数time(3),则可以将其乘以1000。

// Get right now as it's `DateComponents`.
let now = Calendar.current.dateComponents(in: .current, from: Date())

// Create the start of the day in `DateComponents` by leaving off the time.
let today = DateComponents(year: now.year, month: now.month, day: now.day)
let dateToday = Calendar.current.date(from: today)!
print(dateToday.timeIntervalSince1970)

// Add 1 to the day to get tomorrow.
// Don't worry about month and year wraps, the API handles that.
let tomorrow = DateComponents(year: now.year, month: now.month, day: now.day! + 1)
let dateTomorrow = Calendar.current.date(from: tomorrow)!
print(dateTomorrow.timeIntervalSince1970)
Run Code Online (Sandbox Code Playgroud)

您可以减去1得到昨天。


如果您在世界通用时间(UTC,GMT,Z…您给世界通用名称指定的名称)中都需要此功能,请使用以下命令。

let utc = TimeZone(abbreviation: "UTC")!
let now = Calendar.current.dateComponents(in: utc, from: Date())
Run Code Online (Sandbox Code Playgroud)