如何将特定的格林尼治标准时间用于其他时区可以识别的功能 [英] How to use a specific GMT for a function which will be recognised by other time zones
问题描述
我想有一种简单的方法可以做到这一点,我只是还没有弄清楚.
I imagine there's a simple way to do this, I just haven't figured it out yet.
我只想在AEST(格林尼治标准时间+10)上午9点至下午12点之间显示一个按钮.
I want to display a button only between 9am to 12pm AEST (GMT+10).
因此对于AWST(GMT + 8)中的用户,当他们是上午11点时,他们将无法看到该按钮.
So for a user in AWST (GMT+8), they will not be able to see the button when it is 11am for them.
我有特定的时间要使用
let date = Date()
let dateFormatterTime = DateFormatter()
dateFormatterTime.dateFormat = "HH:mm:ss"
dateFormatterTime.timeZone = TimeZone(secondsFromGMT: 36000)
let sydneyTime = dateFormatterTime.string(from: date)
print(sydneyTime)
我有一个适用于每个位置的时区的功能
I have a function which works for the time zone for each location
func CheckTime()->Bool
{
var timeExist: Bool
let calendar = Calendar.current
let startTimeComponent = DateComponents(calendar: calendar, hour: 9)
let endTimeComponent = DateComponents(calendar: calendar, hour: 12, minute: 01)
let now = Date()
let startOfToday = calendar.startOfDay(for: now)
let startTime = calendar.date(byAdding: startTimeComponent, to: startOfToday)!
let endTime = calendar.date(byAdding: endTimeComponent, to: startOfToday)!
if startTime <= now && now <= endTime
{
button.isHidden = false
timeExist = true
print("9am-12pm")
print(sydneyTime)
}
else
{
button.isHidden = true
timeExist = false
print("After 12:01pm")
print(sydneyTime)
}
return timeExist
}
如何使用AEST(sydneyTime)而不是公历时间(Calendar),以便该功能仅在AEST(GMT + 10)期间有效?
How do I use the AEST (sydneyTime) instead of the Gregorian time (Calendar) so the function works only during AEST (GMT+10)?
推荐答案
您可以使用日历方法 func dateComponents(在timeZone:TimeZone中,从日期:Date开始)->DateComponents
并获取所需时区的小时部分.然后,您只需要检查它是否包含在所需的小时范围内即可:
You can use Calendar method func dateComponents(in timeZone: TimeZone, from date: Date) -> DateComponents
and get the hour component at the desired timezone. Then you just need to check if it is contained in the desired hour range:
let timeZone = TimeZone(secondsFromGMT: 36000)!
let hourInAEST = Calendar.current.dateComponents(in: timeZone, from: Date()).hour!
if 9..<12 ~= hourInAEST {
print(true)
} else {
print(false)
}
这篇关于如何将特定的格林尼治标准时间用于其他时区可以识别的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!