根据swift或objective-c中的格林威治标准时间计算到第二天0.00的时间间隔?

Calculate time interval to 0.00 of the next day according to GMT in swift or objective-c?

我试过这样的事情:

var calendar = Calendar.current
var dayFutureComponents = DateComponents()
dayFutureComponents.day = 1 // aka 1 day
var d = calendar.date(byAdding: dayFutureComponents, to: Date())
...//setting of d.hour, d.minute, d.second to zero and finding the difference between 2 dates

问题是例如我当前的 GMT 是 +3。所以结果与我需要 3 小时实现的结果不同。如何解决这个问题?

错过了当我将小时设置为 0 时 - 它根据 GMT 显示(在我的例子中是 3 小时的差异)。当我计算两个日期之间的差异时 - 两个日期具有相同的 "displacement" 所以最终结果应该相同

首先为 UTC 时区创建一个 Calendar。其次获取 startOfDay using the UTC calendar. Third add one day to that date. Then you can useDatemethodtimeIntervalSince(_ Date)` 以计算这两个日期之间的秒数:

extension Calendar {
    static let iso8601UTC: Calendar = {
        var calendar = Calendar(identifier: .iso8601)
        calendar.timeZone = TimeZone(identifier: "UTC")!
        return calendar
    }()
}

extension Date {
    var secondsUntilStartOfDayTomorrowAtUTC: TimeInterval {
        return startOfDayTomorrowAtUTC.timeIntervalSince(self)
    }
    var startOfDayTomorrowAtUTC: Date {
        return Calendar.current.date(byAdding: .day, value: 1, to: startOfDayAtUTC)!
    }
    var startOfDayAtUTC: Date {
        return Calendar.iso8601UTC.startOfDay(for: self)
    }
}

游乐场测试:

TimeZone.current.secondsFromGMT(for: Date()) / 3600 // -2 hours
Date().startOfDayAtUTC          // "Jan 18, 2018 at 10:00 PM"
let finalDate = Date().startOfDayTomorrowAtUTC  // "Jan 19, 2018 at 10:00 PM"
print(finalDate)  // "2018-01-20 00:00:00 +0000\n"
let seconds = Date().secondsUntilStartOfDayTomorrowAtUTC  // 29282.42592203617
let minutes = seconds / 60   // 488.0404320339362
let hours = seconds / 3600   // 8.134007200565604