Как получить сегодняшнюю и завтрашнюю дату в swift 4 - PullRequest
0 голосов
/ 08 января 2019

Как получить текущую дату в unix-epoch? timeIntervalSince1970 печатает текущее время. Есть ли способ узнать текущее время в 12 часов утра?

Например, текущее время: 7 января 2018 года в 17:30. timeIntervalSince1970 напечатает текущее время, т.е. 1546903800000. Текущая дата в системе эпохи будет 7 января 2018 00:00. то есть 1546848000000

Ответы [ 3 ]

0 голосов
/ 08 января 2019

Это можно сделать очень просто, используя следующий код. Нет необходимости в компонентах даты или других сложностях.

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
0 голосов
/ 08 января 2019

Также попробуйте добавить следующий код в расширение даты:

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)!
    }
}
0 голосов
/ 08 января 2019

Я бы сделал это с компонентами.

Предполагается, что вам нужно время в секундах, определенное как 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())
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...