Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
}
like image 410
Michael Quiles Avatar asked Apr 26 '10 21:04

Michael Quiles


2 Answers

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");
like image 135
Kelsey Avatar answered Oct 13 '22 00:10

Kelsey


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

like image 42
Jono Avatar answered Oct 12 '22 23:10

Jono