Swift4systemUptime method

Asked 2 years ago, Updated 2 years ago, 90 views

Thank you very much for letting me know how to get the time that Swift4 has started.When I actually wrote the code, it turned out to be negative or a ridiculous number.
Question 1. Does the systemUptime number include sleep?Will it not be counted if the power is turned off?I don't know the details, so please let me know.
Question 2. Calculation formula using the code you gave me
day=uptime/86400
hour=(uptime-(day*86400))/3600
minute=(uptime-(day*86400+hour*3600))/60
second=(uptime-(day*86400+hour*3600+minute*60))
However, the number displayed was minus or extremely large.Is it wrong?Please let me know.

swift swift4

2022-09-30 19:50

2 Answers

This is a correction due to a change in the contents of the question.

First, the value returned by ProcessInfo().systemUptime is the alias of Double called TimeInterval and returns the number of seconds since the system started.
So you can use this number directly.

If the number of seconds is days, hours, minutes, and seconds, we omit them because they are divided and subtracted, but we calculate each of them and
If you have finished substituting the variables day, hour, minute, and second seconds,
If you want each to be a separate string, you can use the numeric type as the argument for String(), such as String().
 Also, if you want to format it in a fixed format,
String(format: "%d days, %d hours %d minutes %d seconds", day, hour, minute, second)
or
String (format:%d day, %d:%d:%d", day, hour, minute, second)
This allows the entire string to be a single string.

Then place different labels in days, hours, minutes, and seconds and substitute them with .stringValue= or
If you place one label as shown in the sample below and place the whole string in one string with .stringValue=, the label display will be the substituted character.

(Assuming the label is connected to the label on the View in IBOutlet)

class UptimeLabelViewController:UIViewController {
    @IBOutletweakuptimeLabel:UILabel?//UptimeLabelView label and Outlet connection
                                        // Prepare required labels and outlet variables for different days, hours, and minutes

    override viewDidLoad() {
        letuptime —TimeInterval=ProcessInfo().systemUptime
          // The time calculation method is omitted, but based on uptime, day, hour, minute,
          // The value required for the variable second must be set.
        variabletimeString:String
        if(day!=0){
            uptimeString=String (format: "%d days %d hours %d minutes %d seconds", day, hour, minute, second)
        } It's not cool to see else {//0 days.
            uptimeString=String (format: "%d hours %d minutes %d seconds", hour, minute, second)
        } // end if day is present or not
        uptimeLabel.text=uptimeString
    } // end override view DidLoad
} // end class UptimeLabelView

How do you like this?


2022-09-30 19:50

Code similar to the following in your updated question

day=uptime/86400
hour=(uptime-(day*86400))/3600
minute=(uptime-(day*86400+hour*3600))/60
second=(uptime-(day*86400+hour*3600+minute*60))

(Some full-width characters are included. If you don't copy from Xcode and post the actual code as much as possible, it will cause unexpected misunderstanding.)

If uptime retains the value of systemUptime, is the Double type, so wouldn't the number of days be decimalized in the first place?

When converting seconds to days, hours, minutes, and seconds, it is common to use division (commercial) and remainder (residual), but if this remains a floating-point exhibition (Double type), it will be a lot of trouble.

import UIKit

classViewController:UIViewController {

    @IBOutlet weak var label: UILabel!

    override func viewDidLoad(){
        super.viewDidLoad()

        // Use Timer if you want to continue updating the display for the first time.
        showSystemUptime()
    }

    func showSystemUptime(){
        // Write ProcessInfo.processInfo to get a shared instance without creating a new instance each time
        letuptime = ProcessInfo.processInfo.systemUptime
        print(uptime)//->274694.647071527
        // Days divided by 86400 seconds and rounded down decimal places to an integer value
        let days = Int (floor(uptime/86400))
        // The remainder of the same division is the number of seconds in a day, and the one that is close to integer division is trunkingRemainder(dividingBy:) instead of reminder(dividingBy:)
        varrest=uptime.truncatingRemainder (dividingBy:86400)
        // Similarly, calculate the time (integer value) and the number of seconds left in an hour
        let hours = Int (floor(rest/3600))
        rest=rest.truncatingRemainder (dividingBy:3600)
        // Calculate the same number of minutes (integer value) and the number of seconds left in 1 minute
        let minutes = Int (floor(rest/60))
        let seconds = rest.truncatingRemainder (dividingBy:60)
        // For hours, minutes, and seconds, it looks good to display two digits in an integer part, so use String.init(format:)
        letuptimeStr=String(format: "%d days%02d:%02d:%06.3f", days, hours, minutes, seconds)
        print(uptimeStr)//->3days04:18:14.647
        label.text=uptimeStr
    }

}

It's no use displaying systemUptime to less than seconds, so it's better to round it to seconds first.(It may already be done that way, but I don't know what's going on with your question.)

The showSystemUptime() method looks like this if you want to convert it to an integer type first.

func showSystemUptime(){
    letuptime=Int(ProcessInfo.processInfo.systemUptime)
    print(uptime)//->275469
    // The number of days divided by 86400 is the integer type, so you don't have to think about truncating it.
    let days=uptime/86400
    // The remainder of the same division is the number of seconds in the day, and the remainder of the integer is only % calculated
    varrest=uptime%86400
    // Similarly, calculate the time and the number of seconds left in an hour
    let hours = rest/3600
    rest = rest %3600
    // Calculate the number of seconds left in minutes and 1 minute as well
    let minutes = rest/60
    let seconds = rest %60
    // For hours, minutes, and seconds, it looks good to display two digits in an integer part, so use String.init(format:)
    letuptimeStr=String(format: "%d days%02d:%02d:%02d", days, hours, minutes, seconds)
    print(uptimeStr)//->3days04:31:09
    label.text=uptimeStr
}

By the way, when you write a question, write it without any misunderstanding about what you want to do, or if it doesn't work, include the context (uptime is what type and where it comes from) and what you want it to be.

By writing the appropriate questionnaire as much as possible, you won't have to spend extra time on your respondents, and you'll be able to get an accurate answer faster.You may need to get used to what the "appropriate questionnaire" is, but if there are only a few lines, it would be better for you to review them in the hope that they might cause misunderstanding.

I forgot all about it because I don't use it often, but I got a similar question on StackOverflow, which is DateComponentsFormatter.

func showSystemUptime(){
    letuptime = ProcessInfo.processInfo.systemUptime
    print(uptime)//->611924.107341427
    let formatter=DateComponentsFormatter()
    formatter.allowedUnits = [.day, .hour, .minute, .second]
    LetuptimeStr=formatter.string (from:uptime)!
    print(uptimeStr)//->7d 1:58:44
    label.text=uptimeStr
}

Unlike DateFormatter, which allows you to specify a format as a string, you need to select various parameters from a limited selection, so it seems that detailed formatting is not possible.Instead, it seems that units such as hours, minutes, and seconds can be localized according to the user's settings.

Regarding question 1, Apple document does not say that it is very useful, but the definition is "time elapsed since the last OS startup".However, there are reports that it is not counted up while the system is asleep.There are several attempts to get closer to the actual elapsed time, but it is far from wanting to display systemUptime as elapsed time, so if you are interested, you should ask a different question.


2022-09-30 19:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.