C# 字符串转换为时间格式,然后时间跨度每秒递减
代码没有按我计划的那样工作:每个计时器间隔此单元格值减少1秒,然后单元格值将更改,但此代码的值与“00:30:00”相同,没有异常C# 字符串转换为时间格式,然后时间跨度每秒递减,c#,.net,visual-studio,C#,.net,Visual Studio,代码没有按我计划的那样工作:每个计时器间隔此单元格值减少1秒,然后单元格值将更改,但此代码的值与“00:30:00”相同,没有异常 private void timer2_Tick(object sender, EventArgs e) { timer2.Interval = 1000; string ti = row.Cells[4].Value.ToString(); //The cell Value at this command line instance equal
private void timer2_Tick(object sender, EventArgs e)
{
timer2.Interval = 1000;
string ti = row.Cells[4].Value.ToString(); //The cell Value at this command line instance equals "00:30:00"
DateTime tint = DateTime.Parse(ti); //I Want to convert cell value "00:30:00" from string to datetime
DateTime updated = tint.Add(new TimeSpan(0,0,-1)); //Subtract one second from "00:30:00"
row.Cells[4].Value = updated.ToString(@"hh\:mm\:ss").ToString();//Change cell value after subtracting
}
您的问题在这一行:
DateTime updated = tint.Add(new TimeSpan(-0,0,1));
要将时间跨度缩短一秒钟,您需要执行以下操作:
DateTime updated = tint.Add(new TimeSpan(0,0,-1));
//Syntax is TimeSpan(hours,minutes,seconds)
而不是使用
updated.ToString(@“hh\:mm\:ss”).ToString()代码>您应该使用更新的.ToString(@“HH\:mm\:ss”).ToString()代码>因为您的解决方案使用12小时格式,所以会将00:30:00变为12:30:00。我不知道这是否是被通缉的行为
您还需要使用tint.Add(new TimeSpan(0,0,-1))
来减去一秒钟,而不是减去0天,再加上1秒(这就是您当前所做的)。我认为真正的问题是您使用的是日期时间
而不是时间跨度
。字符串“00:30:00”是时间跨度
,而不是日期时间
。像这样的方法应该会奏效:
private void timer2_Tick(object sender, EventArgs e)
{
timer2.Interval = 1000;
//The cell Value at this command line instance equals "00:30:00"
ti = row.Cells[4].Value.ToString();
TimeSpan tint = TimeSpan.Parse(ti);
// Subtract one second
TimeSpan updated = tint.Subtract(TimeSpan.FromSeconds(1));
//Change cell value after subtracting
row.Cells[4].Value = updated.ToString(@"hh\:mm\:ss");
}
或者,如果你真的想耍花招,你可以用一句话来表达:
private void timer2_Tick(object sender, EventArgs e)
{
timer2.Interval = 1000;
row.Cells[4].Value = TimeSpan
.Parse(row.Cells[4].Value.ToString())
.Subtract(TimeSpan.FromSeconds(1))
.ToString(@"hh\:mm\:ss");
}
使用TimeSpan
而不是DateTime
在哪一行我应该用'DateTime'@EhsanSajjadDateTime tint=DateTime.Parse(ti)替换'TimeSpan'
toTimeSpan tint=TimeSpan.Parse(ti)代码>所以我假设您已经尝试过调试。那告诉你什么了?它进入你的事件处理程序了吗?更新的的值是多少?在你把它变成字符串之前,它看起来正确吗?将其转换为字符串后,它看起来正确吗?基本上,您的实际问题是什么?您尝试了哪些方法来解决它?它几乎肯定不会解决您的问题,但更清晰的消除一秒钟的方法是使用tint.AddSeconds(-1)
省去了您每次只需创建一个timespan对象一秒钟的时间,我个人认为它更具可读性。谢谢您的回答,但单元格值不是updated@MohamedWagih它是否未在UI上更新,或者您在调试时看到了它?如果它没有在UI上更新,如果您正在使用WPF,您是否使用了INotifyPropertyChanged
?在我发现另一个逻辑错误后,它显示00:30:00到12:30:00,因为它使用12小时格式,这是不需要的行为,最后一个答案对我有效,因为“00:30:00”是一个TimeSpan
而不是DateTime
非常感谢@ThFiThanks非常感谢rufust这一长语句比以前更好感谢rufus很高兴它有帮助。顺便说一下,在Tick
事件中设置计时器Interval
可能不是最好的方法,除非您试图阻止任何其他方法更改Interval