如何获取.extend
中的当前日期?
unix-epoch
打印当前时间。有什么办法可以获取今天凌晨12点的时间?
例如,当前时间是:2018年1月7日下午5:30。 timeIntervalSince1970
将打印当前时间,即timeIntervalSince1970
。
纪元系统中的当前日期是2018年1月7日00:00 AM。即1546903800000
答案 0 :(得分: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
答案 1 :(得分:4)
我会用组件来做。
假设您需要time(2)
定义的时间(以秒为单位)。如果您需要time(3)
定义的毫秒数,则可以将其乘以1000。
Public function WorkbookIsOpen(byval strFile as string) as Boolean
Dim wbkCurr as excel.workbook
WorkbookIsOpen = false
For each wbkCurr in application.Workbooks
If wbkCurr.name = strfile then
WorkbookIsOpen = true
Exit for
Endif
Next wbkCurr
End function
您可以减去1来得到昨天。
如果您在世界标准时间(UTC,GMT,Z…您给世界标准时间起任何名称)中都需要此,请使用以下命令。
// 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)
答案 2 :(得分:2)
使用此扩展程序获取今天和明天的日期
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())!
}
}
答案 3 :(得分:1)
还尝试在日期扩展中添加以下代码:
extension Date
{
var startOfDay: Date
{
return Calendar.current.startOfDay(for: self)
}
func getDate(dayDifference: Int) -> Date {
var components = DateComponents()
components.day = dayDifference
return Calendar.current.date(byAdding: components, to:startOfDay)!
}
}
答案 4 :(得分:0)
您可以使用以下方法通过添加天数,月数或年数来获取任何日期 通过指定日历组件和该组件的增量值:
func getSpecificDate(byAdding component: Calendar.Component, value: Int) -> Date {
let noon = Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
return Calendar.current.date(byAdding: component, value: value, to: noon)!
}
其中组件可以是以下选项之一: (.day,.month,.year),该值就是您要为此组件添加的金额
例如,要获取下一年的日期,可以使用以下代码:
var nextYear = getSpecificDate(byAdding: .year, value: 1).timeIntervalSince1970