Convert decimal representing time to hour, minutes, seconds

前端 未结 4 1021
一向
一向 2020-12-21 02:45

I have a decimal. The range of this decimal is between 0 and 23.999999. This decimal represents a time. For example, if the decimal is 0.25, then the time it represents is 1

相关标签:
4条回答
  • 2020-12-21 02:50

    Whatever language you use, you can do this using the math functions: MOD and FLOOR/TRUNC

    Let "dec" be the decimal variable

    trunc(mod(dec, 1)) => hours
    trunc(mod(dec * 60, 60)) => minutes
    trunc(mod(dec * 3600, 60)) => seconds
    

    In C#, you can truncate a decimal to int using just explicit casting, e.g.

    int seconds = (int) ((dec * 3600) % 60)
    
    0 讨论(0)
  • 2020-12-21 02:51

    The hours should be pretty easy.

    There are 60 minutes in 1 hour, so get the decimal part, multiply it by 60, and take the integer. Take the decimal again, multiply it again by 60, and you have your seconds.

    For example, let's take the number 20.38490

    We know it's hour 20, or 8 PM.

    This leaves us with the number .38490

    Multiplying with 60, we get 23.094 minutes.

    Multiplying .094 with 60, we get 5 seconds.

    0 讨论(0)
  • 2020-12-21 02:54

    Well, here's an answer in C#, but it's generally the same idea in most languages:

    int hours = (int)hoursDecimal;
    decimal minutesDecimal = ((hoursDecimal - hours) * 60);
    int minutes = (int)minutesDecimal;
    int seconds = (int)((minutesDecimal - minutes) * 60);
    
    0 讨论(0)
  • 2020-12-21 03:13

    you can use the floor function to strip off the hours and leave the minuites and seconds as a fraction of an hour. Then you can use the floor function again to strip off the minuites as a fraction of an hour. you are then left with the seconds ( as fractions of an hour )

    below a simple example to print hours and mins sunrise is in fractional hours since midnight

    printf( "sunrise %ld:%ld, \n", 
                 (long)floor( sunrise ),
                     (long)(floor( sunrise * 60 ) - 60 * floor( sunrise )) );
    
    0 讨论(0)
提交回复
热议问题