How to use a specific GMT for a function which will be recognised by other time zones

主宰稳场 提交于 2021-02-05 08:33:36

问题


I imagine there's a simple way to do this, I just haven't figured it out yet.

I want to display a button only between 9am to 12pm AEST (GMT+10).

So for a user in AWST (GMT+8), they will not be able to see the button when it is 11am for them.

I have the specific time I want to use

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
}

How do I use the AEST (sydneyTime) instead of the Gregorian time (Calendar) so the function works only during AEST (GMT+10)?


回答1:


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


来源:https://stackoverflow.com/questions/62589470/how-to-use-a-specific-gmt-for-a-function-which-will-be-recognised-by-other-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!