Search code examples
c#timespanbattery

What does a Timespan mean when you get decimals in the hours. e.g. 43.02:10:00 and how do I avoid it


So I am trying to log a timespan of the battery life remaining on my device

my method is:

PowerStatus powerStatus = SystemInformation.PowerStatus;
if (powerStatus.BatteryLifeRemaining > -1)
{
     Console.WriteLine(String.Format("Battery Life Remaining {0}",new TimeSpan(0, 0, powerStatus.BatteryLifeRemaining)).ToString());
}

But I get strange values back from time to time like 7.01:44:22

Looking at TimeSpan Constructor

There example shows that:

TimeSpan( 1000, 2000, 3000 )         =     43.02:10:00
TimeSpan( 1000, -2000, -3000 )       =     40.05:50:00
TimeSpan( 999999, 999999, 999999 )   =  42372.15:25:39

But what do these values mean and how can I avoid getting them as they don't make a lot of sense in the real world


Solution

  • The MSDN documentation explains it well. The number preceding the decimal is days and after is hours.

    43.02:10:00
    

    Translates to:

    43 days
    02 hours
    10 minutes
    00 seconds
    

    You can verify this with code:

    var ts = new TimeSpan(1000, 2000, 3000);
    
    Console.WriteLine(ts.TotalDays);  // Output: 43.0902777777778
    Console.WriteLine(ts.Days);       // Output: 43
    
    Console.WriteLine(ts.TotalHours); // Output: 1034.16666666667
    Console.WriteLine(ts.Hours);      // Output: 2