开发者

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.xTri开发者_运维知识库pEstimateLabel.Text = "Driving at this speed the estimated travel time in hours is: " + Time.ToString("0.0") + " hrs";
}


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


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


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

  • Standard TimeSpan Format Strings and
  • Custom TimeSpan Format Strings.

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.)


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).


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.


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.


Create a timespan from you numeric variable:

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

Then, use the ToString method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜