在计时器倒计时中包含小时



我正在尝试创建一个包含小时的倒计时。

private int time = 3660;        
public MainWindow()
{
var vm = new TimerViewModel();
InitializeComponent();
// get display setting - 2 means extended
int displayType = Screen.AllScreens.Length;
// set the windows datacontext
DataContext = vm;
// set up the timedispatcher
dt.Interval = new TimeSpan(0, 0, 1);
dt.Tick += Timer_Tick;
}   
private void Timer_Tick(object sender, EventArgs e)
{
switch(time)
{
case int x when x > 10 && x <= 20:                 
TimerPreview.Foreground = Brushes.Orange;
time--;
break;
.....................
default:
TimerPreview.Foreground = Brushes.LimeGreen;
time--;
break;
}
TimerPreview.Content = string.Format("00:{0:00}:{1:00}",  time / 60, time % 60);
}

我不知道如何使倒计时与小时正确地工作。它在分秒之间非常有效。

TimerPreview.Content = string.Format("{0:00}:{1:00}:{2:00}", time ???, time ??? 60, time % 60);

我尝试了许多组合,但都没有找到解决方案。我错过了什么?非常感谢。

使用3600(一小时中的秒数(,并在分钟上使用模数运算符,就像在秒上一样(因为您希望60分钟显示为新的小时(:

TimerPreview.Content =
string.Format("{0:00}:{1:00}:{2:00}", time / 3600, (time / 60) % 60, time % 60);
//  320 -> 00:05:20
// 7199 -> 01:59:59
// 7201 -> 02:00:01

另一个(可以说更可读(选项是使用TimeSpan来处理格式化:

TimerPreview.Content = TimeSpan.FromSeconds(time).ToString(@"hh:mm:ss");

time3660:时的结果

01:01:00


编辑:感谢@GrantWinney指出TimeSpan的默认字符串格式与上述相同,除非时间跨度大于一天,在这种情况下,它也包括天。所以你可以做:

TimerPreview.Content = TimeSpan.FromSeconds(time).ToString();

最新更新