字符串到时间格式,然后时间跨度每秒减少

时间:2017-03-26 17:57:52

标签: c# .net visual-studio

代码无法正常工作:每个定时器间隔此单元格值减少一​​秒,然后单元格值将更改,但使用此代码时,值与“00:30:00”相同且无异常。< / p>

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
}

3 个答案:

答案 0 :(得分:2)

我认为真正的问题是您使用的是DateTime而不是TimeSpan。你的字符串&#34; 00:30:00&#34;是TimeSpan,而不是DateTime。这样的事情应该有效:

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

答案 1 :(得分:0)

您的问题就在这一行:

DateTime updated = tint.Add(new TimeSpan(-0,0,1));

要将TimeSpan减少一秒,您需要以下内容:

DateTime updated = tint.Add(new TimeSpan(0,0,-1));
//Syntax is TimeSpan(hours,minutes,seconds)

答案 2 :(得分:0)

您应该使用updated.ToString(@"hh\:mm\:ss").ToString();,而不是使用updated.ToString(@"HH\:mm\:ss").ToString();,因为它使用12小时格式,因此您的解决方案会在00:30:00到12:30:00之间转换。我不知道这是否是通缉行为。

此外,您需要使用tint.Add(new TimeSpan(0, 0, -1))减去一秒而不是减去0天并添加1秒(这是您目前所做的)。