将小数小时转换为DD:HH:MM

Wra*_*ath 14 c# datetime

我试图将一个小时的小时数转换为天,小时和分钟.

这就是我到目前为止所做的,它还没有完全存在.如果有意义的话,我需要从小时部分减去小时数?

        /// <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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

解:

    /// <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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 38

您可以使用TimeSpan.FromHours获得时间跨度,然后您拥有所需的一切:

TimeSpan ts = TimeSpan.FromHours(Decimal.ToDouble(dHours));
Run Code Online (Sandbox Code Playgroud)

例如:

int D = ts.Days;
int H = ts.Hours;
int M = ts.Minutes;
Run Code Online (Sandbox Code Playgroud)