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)
这可以使用以下代码非常简单地完成.无需日期组件或其他并发症.
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)
我会用组件来做到这一点。
假设您需要按秒定义的时间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)
| 归档时间: |
|
| 查看次数: |
2092 次 |
| 最近记录: |