Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert double value to a time? C#/ASP.NET [closed]

Tags:

c#

How can I convert double value to time? for example I have this double value val = 0.00295692867015203 and I want to return 4:15.

I have done a lot of research and did not find a solution that worked! Here is a function that I have tried also but it returns 00:00:00:

ConvertFromDecimalToDDHHMM(Convert.ToDecimal(val));

public 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;
    }
}

I am using C# and ASP.NET. I will appreciate any advise.

like image 290
Jaylen Avatar asked Jan 25 '13 18:01

Jaylen


2 Answers

Wow...took me a while to realize you meant "00:04:15.00"....

public static TimeSpan TimeSpan.FromDays(double value) will get you a TimeSpan

And DateTime.Today.AddDays(double value) will get you a date time

like image 75
JerKimball Avatar answered Sep 29 '22 21:09

JerKimball


I think you want something like TimeSpan.FromDays(0.00295692867015203). The TimeSpan function takes a double value and returns TimeSpan object (naturally): http://msdn.microsoft.com/en-us/library/system.timespan.fromdays.aspx.

This TimeSpan object can then be used in date-time arithmetic, like the following:

var now = DateTime.Now; // say, 25/13/2013 12:23:34
var interval = TimeSpan.FromDays(0.00295692867015203); // 4:15
var futureTime = now + interval; // 25/13/2013 12:27:49
like image 30
Noldorin Avatar answered Sep 29 '22 21:09

Noldorin