寻找以数字格式显示时间的更短的方法
本文关键字:方法 时间 显示 数字 格式 寻找 | 更新日期: 2023-09-27 18:11:23
这段代码可以缩短吗?像这样:08:24:09?
而不是像这样8:24.9
我当前的代码:
this.lblClock = new System.Windows.Forms.Label();
this.lblClock.Text = "00:00:00";
时钟节拍:
private void _Clock_Tick(object sender, EventArgs e)
{
DateTime CurrTime = DateTime.Now;
if (CurrTime.Hour > 9 && CurrTime.Minute > 9 && CurrTime.Second > 9)
lblClock.Text = ("" + CurrTime.Hour + ":" + CurrTime.Minute + ":" + CurrTime.Second);
if (CurrTime.Hour < 10 && CurrTime.Minute > 9 && CurrTime.Second > 9)
lblClock.Text = ("0" + CurrTime.Hour + ":" + CurrTime.Minute + ":" + CurrTime.Second);
if (CurrTime.Hour > 9 && CurrTime.Minute > 9 && CurrTime.Second < 10)
lblClock.Text = ("" + CurrTime.Hour + ":" + CurrTime.Minute + ":" + "0" + CurrTime.Second);
if (CurrTime.Hour < 10 && CurrTime.Minute > 9 && CurrTime.Second < 10)
lblClock.Text = ("0" + CurrTime.Hour + ":" + CurrTime.Minute + ":" + "0" + CurrTime.Second);
if (CurrTime.Hour > 9 && CurrTime.Minute < 10 && CurrTime.Second > 9)
lblClock.Text = ("" + CurrTime.Hour + ":" + "0" + CurrTime.Minute + ":" + CurrTime.Second);
if (CurrTime.Hour < 10 && CurrTime.Minute < 10 && CurrTime.Second > 9)
lblClock.Text = ("0" + CurrTime.Hour + ":" + "0" + CurrTime.Minute + ":" + CurrTime.Second);
if (CurrTime.Hour > 9 && CurrTime.Minute < 10 && CurrTime.Second < 10)
lblClock.Text = ("" + CurrTime.Hour + ":" + "0" + CurrTime.Minute + ":" + "0" + CurrTime.Second);
if (CurrTime.Hour < 10 && CurrTime.Minute < 10 && CurrTime.Second < 10)
lblClock.Text = ("0" + CurrTime.Hour + ":" + "0" + CurrTime.Minute + ":" + "0" + CurrTime.Second);
}
你能缩短这个片段吗?
您可以使用DateTime Format "HH:mm:ss"
在标签中显示时间。
lblClock.Text = CurrTime.ToString("HH:mm:ss");
如果你想显示AM/PM,那么你可以这样做:
lblClock.Text = CurrTime.ToString("hh:mm:ss tt");
查看MSDN页面DateTime.ToString(…)
你可以做所有的格式!!…包括"HH:mm:ss"
,这就是你要的