Search code examples
swiftdateutc

Get current local time in UTC and set to Binary operator like >= or <


Bear with me, I'm a newbie to iOS development; I'm currently trying to get the current time in UTC based on the device's local time, and set it in an if / else statement based on the whatever the current time in UTC is.

I've tried the below:

let UTCdate = Date()

if (UTCdate >= 13 && UTCdate < 23 {
   // do something
}

It's giving me the error that "Binary operator '>=' cannot be applied to operands of type 'Date' and 'Int'

I know I'm doing something wrong, just don't know what. Apologies if this has already been asked. I google'd to the best of my abilities.


Solution

  • You need to extract the hour from your date. Date is a timestamp, not an hour. And you need to make sure you extract the hour in the UTC timezone and not locale time.

    The following will do what you need:

    // Create a calendar with the UTC timezone
    var utcCal = Calendar(identifier: Calendar.current.identifier) // or hardcode .gregorian if appropriate 
    utcCal.timeZone = TimeZone(secondsFromGMT: 0)!
    // The current date
    let date = Date()
    // Get the hour (it will be UTC hour)
    let hour = utcCal.component(.hour, from: date)
    if hour >= 13 && hour < 23 {
    
    }
    

    If you just use the current calendar to extra the hour from date you will get the hour in local time. That is the reason we created a new calendar specific to the UTC timezone (since that is your requirement).

    Based on some comments you may not actually want UTC. Simply set the timeZone to whatever timezone you actually need.

    If you want Chicago time, use:

    utcCal.timeZone = TimeZone(identifier: "America/Chicago")!
    

    And an alternate to creating your own calendar instance is to use:

    let hour = Calendar.current.dateComponents(in: TimeZone(secondsFromGMT: 0)!, from: date).hour!
    

    Again, use whatever timezone you need.