Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decimal hours to DD:HH:MM

Tags:

c#

datetime

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;
        }
    }
like image 357
WraithNath Avatar asked Mar 14 '12 09:03

WraithNath


1 Answers

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;
like image 85
Tim Schmelter Avatar answered Oct 08 '22 10:10

Tim Schmelter