Convert time to formatted string in C #

Time.ToString("0.0") displayed as the decimal value of "1.5" instead of 1:30. How can I display it in 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"; } 
+7
c # time string-formatting
source share
7 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:. Now we know that double time changes the code to (if 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"); 
+25
source share

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

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

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

+2
source share

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

+2
source share

Please note that if you work in a 24-hour base, it is 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 is no way to find out AM or PM (if you are not using tt ).

+1
source share

If the time will be floating or double, you will have to. System.Math.Truncate (Time) to get the clock

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

0
source share

Thanks for the answers from guys and girls, I used this DateTime.MinValue.AddHours(Time).ToString("H:mm"); for my program, since it was the easiest to implement.

0
source share

Create a timeline from your numeric variable:

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

Then use the ToString method.

0
source share

All Articles