Search code examples
iosswiftnsdate

How can I check if a date / time is within 1 minute of the current date / time


I have an access token with an expiration time. I would like to check when using my access token, does it expire within a minute.

If it does expire in less than a minute, I would like to take some action.

I am struggling to understand how I can check the date and time against the current date / time.

The exp time on my token looks like 1549103089 but using my auth lib 'AeroGearOAuth2' I can access it and print it out as 2019-02-02 10:13:48 +0000


Solution

  • I assume the number 1549103089 is stored in an Int or Double variable.

    1549103089 represents the number of seconds since 1970/01/01 00:00:00 UTC. Therefore, you can get the current date as the number of seconds since 1970, then subtract the current date from 1549103089. If the number is less than 60 but greater than 0, it means the current date is within one minute before the expiration date.

    let expirationDate: Double = 1549103089
    let currentDate = Date().timeIntervalSince1970
    if (0.0...60).contains(expirationDate - currentDate) {
        // within one minute!
    }