can I convert a label that shows the time into a b

2019-08-24 05:16发布

问题:

I have a label that displays the time and I would like to convert that label.text into a color for the background that changes every time the time changes. Is this possible? My code is below. Example: If the time displayed is 11:23:04 I would like the background color to be changed to #112304. If the time displayed is 11:24:00 I would like the background color to be changed to #112400. etc. etc.

Private Sub Timer1_Tick() Handles Timer1.Tick

    Label1.Text = TimeOfDay

    Label2.Text = System.DateTime.Now.ToString("MM/d/yyy")

End Sub

回答1:

It's possible to create a new color by using the FromArgb. The TimeOfDay property is a TimeSpan which contains a Hour, Minute and Second property.

Color.FromArgb(DateTime.TimeOfDay.Hour, DateTime.TimeOfDay.Minute, DateTime.TimeOfDay.Second)

This will use decimal, so 11:12:13 will be #0B0C0D if you want to use decimal format you'll need to convert it first.



回答2:

First Remove the ":" from the time and then convert it into a hex color

Dim remove = Label1.Text.Replace(":", "")
    Me.BackColor = ColorTranslator.FromHtml("#" & remove)


回答3:

Combine Dmandy's ColorTranslator.FromHtml() approach and format the time as you've already demonstrated with ToString():

Me.BackColor = ColorTranslator.FromHtml(DateTime.Now.ToString("#HHmmss"))