c中根据格林威治标准时间计算到第二天0

c中根据格林威治标准时间计算到第二天0

本文介绍了在swift或objective-c中根据格林威治标准时间计算到第二天0.00的时间间隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过这样的事情:

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 小时.如何解决这个问题?

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?

推荐答案

首先为 UTC 时区创建一个 Calendar.其次使用 UTC 日历获取 startOfDay.第三次在该日期上加一天.然后你可以使用DatemethodtimeIntervalSince(_ Date)`来计算这两个日期之间的秒数:

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

这篇关于在swift或objective-c中根据格林威治标准时间计算到第二天0.00的时间间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:04