我正在用C#编写一个NetcafeProgram,我想获取当前的DateTime。我想要这样的输出(小时分钟数)“0.25”。我有当前的DateTime,但我想在labelTime_1中显示为(hr.mins)“0.25”,但它无法正常工作。这是我使用的命令
starttime_1 = DateTime.Now.ToString("h:mm:ss tt");
然后我将其更改为
starttime_1 = DateTime.Now.ToString("h.mm");
然后我想得到这样的持续时间
TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
但这给了我错误。
这是My Formv的屏幕截图:
我想要时间贴在该“已过去的时间”标签上,但是它不起作用。这是BtnStop1的编码
private void btnStop_1_Click(object sender, EventArgs e)
{
//string duration = Convert.ToInt32(((starttime_1) - (endtime_1)));
gbx_1.BackColor = Color.LimeGreen;
btnStop_1.Enabled = false;
//endtime_1 = DateTime.Now.ToString("h:mm:ss tt");
//TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
endtime_1 = DateTime.Now.ToString("h.mm tt");
TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
lblTime_1.Text = Convert.ToString(duration);
string var = "Cabin One is Free";
btnStart_1.Enabled = true;
HP_1.Enabled = true;
CR_1.Enabled = true;
reader = new SpeechSynthesizer();
reader.SpeakAsync(var);
}
BtnStart的编码
private void btnStart_1_Click(object sender, EventArgs e)
{
gbx_1.BackColor = Color.Red;
btnStart_1.Enabled = false;
//starttime_1 = DateTime.Now.ToString("h:mm:ss tt");
starttime_1 = DateTime.Now.ToString("h.mm tt");
lblTime_1.Text = "CountingTime";
string var = "Cabin One is Occupied";
reader = new SpeechSynthesizer();
reader.SpeakAsync(var);
HP_1.Enabled = false;
CR_1.Enabled = false;
}
这是我的变量
public string starttime_1;
public string starttime_2;
public string starttime_3;
public string starttime_4;
public string starttime_5;
public string starttime_6;
public string endtime_1;
public string endtime_2;
public string endtime_3;
public string endtime_4;
public string endtime_5;
public string endtime_6;
最佳答案
我强烈建议您将变量类型更改为DateTime?
。最好以原始类型存储数据,然后在显示时执行转换为字符串的操作。这样,当您需要持续时间时,就不会解析回DateTime
。您可以处理要在基础数据上进行的任何舍入。
因此,您对string
的转换应处于堆栈的最高级别。这将使您的代码更整洁,并在以后适当时更易于从UI重构逻辑。
关于c# - 如何添加自定义时间格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25511378/