Michael Quiles
Michael Quiles

Reputation: 71

Convert a Time to a formatted string in C#

Time.ToString("0.0") shows up as a decimal "1.5" for instead of 1:30. How can I get it to display in a time format?

private void xTripSeventyMilesRadioButton_CheckedChanged(object sender, EventArgs e)
{
    //calculation for the estimated time label
    Time = Miles / SeventyMph; 
    this.xTripEstimateLabel.Visible = true;
    this.xTripEstimateLabel.Text = "Driving at this speed the estimated travel time in hours is: " + Time.ToString("0.0") + " hrs";
}

Upvotes: 7

Views: 26307

Answers (7)

Adilson de Almeida Jr
Adilson de Almeida Jr

Reputation: 2755

Create a timespan from you numeric variable:

TimeSpan ts = new TimeSpan(Math.Floor(Time), (Time - Math.Floor(Time))*60);

Then, use the ToString method.

Upvotes: 0

Heinzi
Heinzi

Reputation: 172448

I guess that Time is of type TimeSpan? In that case, the documentation of TimeSpan.ToString can help you, in particular the pages

If Time is a numeric data type, you can use TimeSpan.FromHours to convert it to a TimeSpan first.

(EDIT: TimeSpan format strings were introduced in .NET 4.)

Upvotes: 2

Michael Quiles
Michael Quiles

Reputation: 71

Thanks for all of the responses guys and gals i used this DateTime.MinValue.AddHours(Time).ToString("H:mm");for my program since it was the easiest one to implement.

Upvotes: 0

escargot agile
escargot agile

Reputation: 22389

Note that if you work in a 24-hour base, it's very important to use HH:mm and NOT hh:mm.

Sometimes I mistakenly write hh:mm, and then instead of "13:45" I get "01:45", and there's no way to know whether it's AM or PM (unless you use tt).

Upvotes: 1

Kelsey
Kelsey

Reputation: 47766

Time.ToString("hh:mm")

Formats:

HH:mm  =  01:22  
hh:mm tt  =  01:22 AM  
H:mm  =  1:22  
h:mm tt  =  1:22 AM  
HH:mm:ss  =  01:22:45  

EDIT: Since now we know the time is a double change the code to (assuming you want hours and minutes):

// This will handle over 24 hours
TimeSpan ts= System.TimeSpan.FromHours(Time);
string.Format("{0}:{1}", System.Math.Truncate(ts.TotalHours).ToString(), ts.Minutes.ToString());

or

// Keep in mind this could be bad if you go over 24 hours
DateTime.MinValue.AddHours(Time).ToString("H:mm");

Upvotes: 27

Gabriel Guimarães
Gabriel Guimarães

Reputation: 2744

If time is float or double you'll have to. System.Math.Truncate(Time) to get the hours

and then (Time - System.Math.Truncate(Time))* 60 to get the minutes.

Upvotes: 0

Jono
Jono

Reputation: 2054

If Time is a System.Double, then System.TimeSpan.FromHours(Time).ToString();

Upvotes: 2

Related Questions