Get current time and set a value in a combobox

2019-09-06 00:53发布

问题:

I´m coding in C# and have done a Windows form with a few texteboxes and a combobox. I want to create a method that gets the current time and depending on the time sets the value in the combobox. In the combobox there are three values:

TimeZone 1
TimeZone 2
TimeZone 3

I have a code that gets the current time:
string CurrentTime = DateTime.Now.ToString("hh:mm");

And want to create a if statment (if its the best?) that gets the current time and sets the value in the combobox.

if the time are:
06:00 - 14:00 the combobox will get the value TimeZone 1
14:01 - 22:00 the combobox will get the value TimeZone 2
22:01 - 05:59 the combobox will get the value TimeZone 3

Any ideas of how to do this?

回答1:

Literally what you said there in the question. Dont attempt to convert it to string and parse it again, it will just make your life harder. Here is a sample code logic

   var now = DateTime.Now;
   if (now.Hours >=6 && now.Hours <=14)
    .....
   else if (now.Hours > 14 && now.Hours < = 22)
    .........
   else
    ........


回答2:

Try this

int hours =  DateTime.Now.Hour;

if(hours >= 6 and hours <= 14)
{
combobox1.SelectedIndex = 0; //Assuming the TimeZone 1 is the first item.
}
else if(hours > 14 and hours <= 22)
{
combobox1.SelectedIndex = 1; //Assuming the TimeZone 2 is the second item.
}
else
{
combobox1.SelectedIndex = 2; //Assuming the TimeZone 3 is the third item.
}


回答3:

string CurrentTime = DateTime.Now.ToString("hh:mm");

if(Convert.ToInt32(CurrentTime.Split(':')[0])>5||Convert.ToInt32(CurrentTime.Split(':')[0])<=14)
    Combobox.SelectedValue="TimeZone 1";
else if(Convert.ToInt32(CurrentTime.Split(':')[0])>=14||Convert.ToInt32(CurrentTime.Split(':')[0])<=22)
     Combobox.SelectedValue="TimeZone 2";
else if(Convert.ToInt32(CurrentTime.Split(':')[0])>=22||Convert.ToInt32(CurrentTime.Split(':')[0])<6)
     Combobox.SelectedValue="TimeZone 3";


标签: c# forms