tags:

views:

208

answers:

3

I need a method in c# that makes me a string that look like a datetime out of a double/float.

for example

1.5 -> 01:30 2.8 -> 02:48 25.5 -> 25:30 (note: don't display as day, display full hours even its more than 24)

+5  A: 

It sounds to me like you don't want a DateTime - you want a TimeSpan:

TimeSpan ts = TimeSpan.FromMinutes(x);

or

TimeSpan ts = TimeSpan.FromHours(x);

(depending on your exact requirement).

Note that "2.8" won't be exactly 2.8, so you may not get exactly the result you expect - for the normal reasons of floating point bases etc.

Although there's no custom formatting for TimeSpan values in currently released version of the framework, it's coming in .NET 4.0.

Jon Skeet
Jon, please stop skeeting me ;-)
Konamiman
+2  A: 

Try the following:

string ToTime(double hours)
{
    var span=TimeSpan.FromHours(hours);
    return string.Format("{0}:{1:00}:{2:00}",
        (int)span.TotalHours, span.Minutes, span.Seconds);
}

Or if you don't want seconds:

string.Format("{0}:{1:00}", (int)span.TotalHours, span.Minutes)
Konamiman
A: 
string convert(double time)
{
    int hours = (int)Math.Floor(time);
    int minutes = Convert.ToInt32( (time-Math.Floor(time)) * 60 );

    return String.Format( "{0}:{1}", hours, minutes );
}
thrag