簡體   English   中英

如何在swift 4中獲得今天和明天的日期

[英]How to get the today's and tomorrow's date in swift 4

如何在unix-epoch獲取當前日期? timeIntervalSince1970打印當前時間。 有什么辦法可以得到今天凌晨 12 點的時間嗎?

例如,當前時間是:2018 年 1 月 7 日下午 5:30。 timeIntervalSince1970將打印當前時間,即1546903800000 紀元系統中的當前日期為 2018 年 1 月 7 日上午 00:00。 1546848000000

這可以使用以下代碼非常簡單地完成。 不需要日期組件或其他復雜功能。

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

我會用組件來做到這一點。

假設您需要 time time(2)定義的time(2)以秒為單位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)

你可以通過減去 1 得到昨天。


如果您需要在世界時(UTC、GMT、Z...無論您給世界時間起什么名字),請使用以下內容。

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

使用此擴展程序獲取今天和明天的日期

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())!
   }
}

還可以嘗試在日期擴展中添加以下代碼:

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)!
    }
}

通過指定日歷組件和該組件的增量值,您可以使用以下方法通過添加天數或月數或年數來獲取任何日期:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM