如何使用 TimeOfDay 进行 5 分钟倒计时

How to make 5 minute countdown using TimeOfDay

股市图表上的烛台每分钟都会创建一次。我创建了一个倒计时计时器,告诉我在创建下一个烛台之前还剩多少秒。

//logic for 1 min candlestick
const int MINUTE = 60;
int currentSecond = DateTime.UtcNow.Second;
int nextMin = MINUTE - currentSecond;
minuteLabel.Text = nextMin.ToString();

该图表还可以每 5 分钟显示一次烛台,以提供不同的视角。因此,在这种情况下,每 5 分钟创建一个烛台。这就是我遇到的麻烦。如何创建倒计时计时器以显示在创建下一个烛台之前还剩多少时间?这是我目前所拥有的:

//inefficient logic for 5 min candlestick
int currentMinute = DateTime.UtcNow.Minute;
int nextFiveMin;

if (currentMinute >= 0 && currentMinute < 5) {
     nextFiveMin = ((5 * MINUTE) - (currentMinute * MINUTE)) - currentSecond;
}
else if(currentMinute >= 5 && currentMinute < 10) {
     nextFiveMin = ((10 * MINUTE) - (currentMinute * MINUTE)) - currentSecond;
}
else if (currentMinute >= 10 && currentMinute < 15) {
     nextFiveMin = ((15 * MINUTE) - (currentMinute * MINUTE)) - currentSecond;
}
//etc all the way to currentMinute > 55

TimeSpan t = TimeSpan.FromSeconds(nextFiveMin);
fiverLabel.Text = t.ToString(@"mm\:ss");

虽然这段代码工作正常,但我认为可能有一种我想不到的更简单的实现方法。

你可以这样做:

int currentMinute = DateTime.UtcNow.Minute;
int diffMinutes   = (currentMinute/5 +1) * 5;
int nextFiveMin   = ((diffMinutes * MINUTE) - (currentMinute * MINUTE)) - currentSecond;

另一种方法:

private void timer1_Tick(object sender, EventArgs e)
{
    // from the current time, strip the seconds, then add one minute:
    DateTime dt = DateTime.Today.Add(new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0)).AddMinutes(1);

    // keep adding minutes until it's a multiple of 5
    while (dt.Minute % 5 != 0)
    {
        dt = dt.AddMinutes(1);
    }

    // display how much time until the next five minute mark:
    TimeSpan t = dt.Subtract(DateTime.Now);  
    fiverLabel.Text = t.ToString(@"mm\:ss");
}