【问题标题】:How to make 5 minute countdown using TimeOfDay如何使用 TimeOfDay 进行 5 分钟倒计时
【发布时间】:2021-04-09 17:53:06
【问题描述】:

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

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

虽然这段代码运行良好,但我认为可能有一种我想不到的更简单的方法来实现它。

【问题讨论】:

    标签: c# datetime timer stock


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

      【解决方案2】:

      另一种方法:

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

      【讨论】:

        猜你喜欢
        • 2021-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 2015-06-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多