Convert a Time to a formatted string in C#

c#, string-formatting, time

Solution

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");

Problem

`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"; } ```

Original source