我正在写一个时钟程序而且我有些困扰。
我有一个标签(TVGentTimeLabel)给我当前时间。
我想做的是时间是08:45:00到10:45:00,我的时钟是红色
当时间介于10:45:01和23:59:59之间时,时钟为绿色,否则为白色
这是我现在的代码:
Sub Timertijd_Tick(sender As Object, e As EventArgs) Handles Timertijd.Tick
TVGentTimeLabel.Text = TimeOfDay.ToString("HH:mm:ss")
If TVGentTimeLabel.Text = "08:45:00" Or TVGentTimeLabel.Text = "08:45:01" Then
TVGentTimeLabel.ForeColor = Color.Red
ElseIf TVGentTimeLabel.Text = "10:45:01" Or TVGentTimeLabel.Text = "10:45:02" Then
TVGentTimeLabel.ForeColor = Color.Green
ElseIf TVGentTimeLabel.Text = "00:00:01" Or TVGentTimeLabel.Text = "00:00:02" Then
TVGentTimeLabel.ForeColor = Color.White
End If
End Sub
我现在的问题是当程序在不同的时间启动时,它将是正常使用的颜色(在我的情况下为黑色)
请有人帮忙
答案 0 :(得分:2)
代码期望计时器准确地在一秒或2秒内打勾,当它没有时,代码没有办法处理它。由于您正在评估时间,因此您应该评估TimeSpan
,而不是字符串:
Dim ts = DateTime.Now.TimeOfDay
Dim tsA = New TimeSpan(8, 45, 0) ' note: AM. add 12 for PM traps
Dim tsB = New TimeSpan(10, 45, 0)
Dim tsC = New TimeSpan(12, 59, 59)
If ts >= tsA AndAlso ts <= tsB Then
' red
ElseIf ts > tsB AndAlso ts <= tsC Then
'green
Else
'white
End If
答案 1 :(得分:2)
根据您目前的情况,这应该有效
Private Sub Timertijd_Tick(sender As Object, e As EventArgs) Handles Timertijd_Tick
Dim d As Date = TimeOfDay
TVGentTimeLabel.Text = d.ToString("HH:mm:ss")
If d >= #8:45:00 AM# And d <= #10:45:00 AM# Then
TVGentTimeLabel.ForeColor = Color.Red
ElseIf d >= #10:45:01 AM# And d <= #11:59:59 PM# Then
TVGentTimeLabel.ForeColor = Color.Green
Else
TVGentTimeLabel.ForeColor = Color.White
End If
End Sub
答案 2 :(得分:0)
您只需在经过一段时间后设置标签的颜色。如果你启动它,它将是一个黑色,直到它通过你的IF structures
之一。尝试将timeOfDay
作为日期而不是字符串处理。
Sub Timertijd_Tick(sender As Object, e As EventArgs) Handles Timertijd.Tick
If DateTime.Now.TimeOfDay >= new TimeSpan(8,45,0) AndAlso DateTime.Now.TimeOfDay <= New TimeSpan(10,45,0) Then
TVGentTimeLabel.ForeColor = Color.Red
ElseIf DateTime.Now.TimeOfDay >= new TimeSpan(10,45,0) AndAlso DateTime.Now.TimeOfDay <= New TimeSpan(23,59,59) Then
TVGentTimeLabel.ForeColor = Color.Green
ElseIf DateTime.Now.TimeOfDay >= new TimeSpan(0,0,0) AndAlso DateTime.Now.TimeOfDay <= new TimeSpan(8,44,59)
TVGentTimeLabel.ForeColor = Color.White
End Sub