如何在swift 4中获得今天和明天的日期 [英] How to get the today's and tomorrow's date in swift 4
问题描述
如何在unix-epoch
中获取当前日期?timeIntervalSince1970
打印当前时间.有什么办法可以得到今天凌晨 12 点的时间吗?
How to get the current date in unix-epoch
?
timeIntervalSince1970
prints the current time. Is there any way to get today's time at 12 AM?
例如,当前时间是:2018 年 1 月 7 日下午 5:30.timeIntervalSince1970
将打印当前时间,即 1546903800000
.纪元系统中的当前日期为 2018 年 1 月 7 日上午 00:00.即 1546848000000
For example, The current time is : Jan 7, 2018 5:30 PM. timeIntervalSince1970
will print the current time i.e. 1546903800000
.
Current date in epoch system will be Jan 7, 2018 00:00 AM. i.e 1546848000000
推荐答案
我会用组件来做到这一点.
I would do this with components.
假设您需要 time(2)
定义的时间(以秒为单位).如果您需要 time(3)
定义的毫秒数,然后你可以把它乘以 1000.
Assuming you need time in seconds as defined by time(2)
. If you need in milliseconds as defined by time(3)
, then you can multiply it out by 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)
你可以通过减去 1 得到昨天.
You can get yesterday by subtracting 1.
如果您需要在世界时(UTC、GMT、Z...无论您给世界时间起什么名字),请使用以下内容.
If you need this in the universal time (UTC, GMT, Z… whatever name you give universal time), then use the following.
let utc = TimeZone(abbreviation: "UTC")!
let now = Calendar.current.dateComponents(in: utc, from: Date())
这篇关于如何在swift 4中获得今天和明天的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!