简体   繁体   中英

How to use time values in select case statement in vb.net

I want to check the current time with the half an hour time slots (total of 48 starts from 00:00,00:30,01:00,....23:30). Is it possible using select case statement. If not any other suggestions please?

I am storing the current time in an object.

    Dim datime As DateTime = DateTime.Now.ToString("t") 

now i need to do conditional check on this variable. under whichever the time slot the variable belongs, i need to write a value under corresponding timeslot.

It is possible to use the VB.NET Date data type with the Select... Case statement, however this would not be a very good way to solve your problem as you would be forced to compare both the date portion and the time portion together. (You could change the date to a "dummy" value to compare against a known date, but it would still be a rather inefficient and overly long way of doing this.)

I would suggest instead using TimeOfDay to get the duration past midnight of the current date:

Dim timeOfDay As TimeSpan = DateTime.Now.TimeOfDay

Now you can normalize it to one of your 48 values:

Dim slot As Integer = timeOfDay.Hours * 2 + timeOfDay.Minutes \ 30

This should result in a slot value ranging from 0 (when the TimeSpan is less than 00:30:00) to 47 (when the TimeSpan is greater than 23:29:00).

Dim datime As DateTime = DateTime.Now
Dim timeSlot As Integer = datetime.Hour * 2 + (If(datetime.Minute > 30, 1, 0)) 
Select Case timeSlot 'ranges from 0 to 47
    Case 0
        ...
End Select

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM