Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

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

I tried something like this:

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

The problem is for example my current GMT is +3. So the result differs from one I need to achieve by 3 hours. How to fix this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First create a Calendar for the UTC timezone. Second get the startOfDay using the UTC calendar. Third add one day to that date. Then you can useDatemethodtimeIntervalSince(_ Date)` to calculate the amount of seconds between those two dates:

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

Playground Testing:

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
"
let seconds = Date().secondsUntilStartOfDayTomorrowAtUTC  // 29282.42592203617
let minutes = seconds / 60   // 488.0404320339362
let hours = seconds / 3600   // 8.134007200565604

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...