Swift – System Uptime

I specifically use this in an iOS app but you should be able to use this in iOS or Mac OS

The first function will get the Uptime of the system in seconds while the second function will convert the seconds into a easier to read/understand format.

func uptime() -> time_t {
        var boottime = timeval()
        var mib: [Int32] = [CTL_KERN, KERN_BOOTTIME]
        var size = MemoryLayout<timeval>.stride
        
        var now = time_t()
        var uptime: time_t = -1
        
        time(&now)
        if (sysctl(&mib, 2, &boottime, &size, nil, 0) != -1 && boottime.tv_sec != 0) {
            uptime = now - boottime.tv_sec
        }
        return uptime
    }
   
func PrintSecondsToHumanReadable (seconds:Int) -> String  {
        let sDays = String((seconds / 86400)) + " days"
        let sHours = String((seconds % 86400) / 3600) + " hours"
        let sMinutes = String((seconds % 3600) / 60) + " minutes"
        let sSeconds = String((seconds % 3600) % 60) + " seconds"
        
        var sHumanReadable = ""
        
        if ((seconds / 86400) > 0)
        {
            sHumanReadable = sDays + ", " + sHours + ", " + sMinutes + ", " + sSeconds
        }
        else if (((seconds % 86400) / 3600) > 0)
        {
            sHumanReadable = sHours + ", " + sMinutes + ", " + sSeconds
        }
        else if (((seconds % 3600) / 60) > 0)
        {
            sHumanReadable = sMinutes + ", " + sSeconds
        }
        else if (((seconds % 3600) % 60) > 0)
        {
            sHumanReadable = sSeconds
        }
        return sHumanReadable
    }
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.