将时间转换为 C# 中的格式化字符串 [英] Convert a Time to a formatted string in C#

查看:36
本文介绍了将时间转换为 C# 中的格式化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Time.ToString("0.0") 显示为十进制1.5"而不是 1:30.如何让它以时间格式显示?

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

推荐答案

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,请将代码更改为(假设您需要小时和分钟):

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

// Keep in mind this could be bad if you go over 24 hours
DateTime.MinValue.AddHours(Time).ToString("H:mm");

这篇关于将时间转换为 C# 中的格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆