Im trying to convert a decmial number of hours to days, hours and minutes.
This is what I have so far, its not quite there yet. I need to subtract the number of hours from the days from the hours part if that makes sense?
/// <summary>
/// Converts from a decimal value to DD:HH:MM
/// </summary>
/// <param name="dHours">The total number of hours</param>
/// <returns>DD:HH:MM string</returns>
public static string ConvertFromDecimalToDDHHMM(decimal dHours)
{
try
{
decimal hours = Math.Floor(dHours); //take integral part
decimal minutes = (dHours - hours) * 60.0M; //multiply fractional part with 60
int D = (int)Math.Floor(dHours / 24);
int H = (int)Math.Floor(hours);
int M = (int)Math.Floor(minutes);
//int S = (int)Math.Floor(seconds); //add if you want seconds
string timeFormat = String.Format("{0:00}:{1:00}:{2:00}", D, H, M);
return timeFormat;
}
catch (Exception)
{
throw;
}
}
SOLUTION:
/// <summary>
/// Converts from a decimal value to DD:HH:MM
/// </summary>
/// <param name="dHours">The total number of hours</param>
/// <returns>DD:HH:MM string</returns>
public static string ConvertFromDecimalToDDHHMM(decimal dHours)
{
try
{
decimal hours = Math.Floor(dHours); //take integral part
decimal minutes = (dHours - hours) * 60.0M; //multiply fractional part with 60
int D = (int)Math.Floor(dHours / 24);
int H = (int)Math.Floor(hours - (D * 24));
int M = (int)Math.Floor(minutes);
//int S = (int)Math.Floor(seconds); //add if you want seconds
string timeFormat = String.Format("{0:00}:{1:00}:{2:00}", D, H, M);
return timeFormat;
}
catch (Exception)
{
throw;
}
}
You could use TimeSpan.FromHours
to get the timespan, then you have all you need:
TimeSpan ts = TimeSpan.FromHours(Decimal.ToDouble(dHours));
For example:
int D = ts.Days;
int H = ts.Hours;
int M = ts.Minutes;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With