Time.ToString("0.0")
显示为小数“1.5”代替1:30。如何让它以时间格式显示?
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";
}
答案 0 :(得分:25)
Time.ToString("hh:mm")
格式:
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
编辑:从现在起我们知道时间是double
将代码更改为(假设您需要小时和分钟):
// 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());
或
// Keep in mind this could be bad if you go over 24 hours
DateTime.MinValue.AddHours(Time).ToString("H:mm");
答案 1 :(得分:2)
我猜Time
的类型为TimeSpan
?在这种情况下,the documentation of TimeSpan.ToString可以为您提供帮助,特别是页面
如果Time是数字数据类型,您可以先使用TimeSpan.FromHours将其转换为TimeSpan。
(编辑:在.NET 4中引入了TimeSpan格式字符串。)
答案 2 :(得分:2)
如果Time
是System.Double
,那么System.TimeSpan.FromHours(Time).ToString();
答案 3 :(得分:1)
请注意,如果您在24小时工作,则使用HH:mm
而不是hh:mm
非常重要。
有时候我错误地写hh:mm
,而不是“13:45”我得到“01:45”,并且无法知道它是AM还是PM(除非你使用tt
)。
答案 4 :(得分:0)
如果时间是浮动或双倍,你必须。 System.Math.Truncate(时间)获取小时数
然后(Time - System.Math.Truncate(Time))* 60 得到分钟。
答案 5 :(得分:0)
感谢所有回复的家伙和女孩我使用此DateTime.MinValue.AddHours(Time).ToString("H:mm");
作为我的程序,因为它是最容易实现的。
答案 6 :(得分:0)
从数字变量创建一个时间跨度:
TimeSpan ts = new TimeSpan(Math.Floor(Time), (Time - Math.Floor(Time))*60);
然后,使用ToString方法。