在 C# 中将时间转换为格式化字符串
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";
}
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";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
格式:
编辑:从现在起我们知道时间是
double
,将代码更改为(假设您需要小时和分钟):或
Formats:
EDIT: Since now we know the time is a
double
change the code to (assuming you want hours and minutes):or
如果
Time
是System.Double
,则System.TimeSpan.FromHours(Time).ToString();
If
Time
is aSystem.Double
, thenSystem.TimeSpan.FromHours(Time).ToString();
我猜
Time
的类型是TimeSpan
?在这种情况下,TimeSpan.ToString 的文档可以帮助您,特别是页面如果时间是数字数据类型,则可以使用 TimeSpan.FromHours 首先将其转换为 TimeSpan。
(编辑:TimeSpan 格式字符串是在 .NET 4 中引入的。)
I guess that
Time
is of typeTimeSpan
? In that case, the documentation of TimeSpan.ToString can help you, in particular the pagesIf 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.)
请注意,如果您在 24 小时制中工作,则使用
HH:mm
而不是hh:mm
非常重要。有时我错误地写了
hh:mm
,然后我得到的不是“13:45”而是“01:45”,并且无法知道现在是上午还是下午(除非您使用tt
)。Note that if you work in a 24-hour base, it's very important to use
HH:mm
and NOThh: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 usett
).如果时间是浮动或双倍,你就必须这样做。
System.Math.Truncate(Time) 获取小时数
,然后 (Time - System.Math.Truncate(Time))* 60
获取会议记录。
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.
感谢所有的回复,我在我的程序中使用了这个
DateTime.MinValue.AddHours(Time).ToString("H:mm");
,因为它是最容易实现的一个。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.从数值变量创建时间跨度:
然后,使用 ToString 方法。
Create a timespan from you numeric variable:
Then, use the ToString method.