Convert seconds to days, minutes, and hours in Obj-c

后端 未结 11 2393
[愿得一人]
[愿得一人] 2020-12-13 01:16

In objective-c, how can I convert an integer (representing seconds) to days, minutes, an hours?

Thanks!

11条回答
  •  不知归路
    2020-12-13 01:51

    This is my algorithm for converting seconds to seconds, minutes and hours (only using the total amount of seconds and the relation between each of them):

    int S = totalSeconds % BaseSMH
    
    int M = ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2) / BaseSMH
    
    int H = (totalSeconds - totalSeconds % BaseSMH - ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2)) / BaseSMH ^ 2
    

    And here follows my explanation of it:

    Test time converted to seconds: HH:MM:SS = 02:20:10 => totalSeconds = 2 * 3600 + 20 * 60 + 10 = 7200 + 1200 + 10 = 8410

    The base between seconds -> minutes and minutes -> hours is 60 (from seconds -> hours it's 60 ^ 2 = 3600).

    int totalSeconds = 8410
    const int BaseSMH = 60
    

    Each unit (here represented by a variable) can be calculated by removing the previous unit (expressed in seconds) from the total amount of seconds and divide it by its relation between seconds and the unit we are trying to calculate. This is what each calulation looks like using this algorithm:

    int S = totalSeconds % BaseSMH
    
    int M = ((totalSeconds - S) % BaseSMH ^ 2) / BaseSMH
    
    int H = (totalSeconds - S - M * BaseSMH) / BaseSMH ^ 2
    

    As with all math we can now substitute each unit in the minutes and hours calculations with how we calculated the previous unit and each calculation will then look like this (remember that dividing with BaseSMH in the M calculation and multiplying by BaseSMH in the H calulation cancels each other out):

    int S = totalSeconds % BaseSMH
    
    int M = ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2) / BaseSMH
    
    int H = (totalSeconds - totalSeconds % BaseSMH - ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2)) / BaseSMH ^ 2
    

    Testing with the "totalSeconds" and "BaseSMH" from above will look like this:

    int S = 8410 % 60
    
    int M = ((8410 - 8410 % 60) % 60 ^ 2) / 60
    
    int H = (8410 - 8410 % 60 - ((8410 - 8410 % 60) % 60 ^ 2)) / 60 ^ 2
    

    Calculating S:

    int S = 8410 % 60 = 10
    

    Calculating M:

    int M = ((8410 - 8410 % 60) % 60 ^ 2) / 60 
    = ((8410 - 10) % 3600) / 60 
    = (8400 % 3600) / 60 
    = 1200 / 60 
    = 20
    

    Calculating H:

    int H = (8410 - 8410 % 60 - ((8410 - 8410 % 60) % 60 ^ 2)) / 60 ^ 2 
    = (8410 - 10 - ((8410 - 10) % 3600)) / 3600
    = (8400 - (8400 % 3600)) / 3600
    = (8400 - 1200) / 3600
    = 7200 / 3600
    = 2
    

    With this you can add whichever unit you want, you just need to calculate what the relation is between seconds and the unit you want. Hope you understand my explanations of each step. If not, just ask and I can explain further.

提交回复
热议问题