finding a time range using case statement - vb.net

good evening everyone...
could anyone help me on this?
With a "time value", eg. 08:00:00...
i want to find the range that this value falls in using case statement...
i am not good in using the time format...
anyone can help?
This is just an example: (the code is not working...is just an example)
datime = Now().ToString("hh:mm:ss")
Select Case datime
Case "08:00:00" To "09:00:00"
lblRange.Text = i.ToString()
Case "09:00:01" To "09:14:59"
lblRange.Text = (i - 0.25).ToString()
Case "09:15:00" To "09:29:59"
lblRange.Text = (i - 0.5).ToString()

If you don't follow Tim's advice you can use this
Dim timeToCheck As DateTime = #7:10:00 PM#
Select Case timeToCheck.TimeOfDay
Case New TimeSpan(8, 0, 0) To New TimeSpan(9, 0, 0)
Stop
Case New TimeSpan(9, 0, 1) To New TimeSpan(9, 14, 59)
Stop
Case New TimeSpan(9, 15, 0) To New TimeSpan(9, 29, 59)
Stop
Case New TimeSpan(19, 0, 0) To New TimeSpan(19, 14, 59)
Stop
Case Else
Stop
End Select
You do NOT want to use strings.

In this case i wouldn't use the Select...Case statement, it should be used with simple conditions only. You can use an If-Else instead.
But since you're actually checking if a given time is between a range you could also use following code which uses LINQ.
First you need to define a collection which holds all ranges. You can use a List(Of YourClass) or even an array of an anoymous type:
Dim ranges = {
New With {.Start = TimeSpan.FromHours(8), .End = TimeSpan.FromHours(9)},
New With {.Start = New TimeSpan(9, 0, 1), .End = New TimeSpan(9, 14, 59)},
New With {.Start = New TimeSpan(9, 15, 0), .End = New TimeSpan(9, 29, 59)}
}
You want to compare TimeSpans, you get the current time by Date.Now.TimeOfDay.
Dim now As TimeSpan = Date.Now.TimeOfDay
Dim matchingRange = ranges.
FirstOrDefault(Function(r) now >= r.Start AndAlso now <= r.End)
Enumerable.FirstOrDefault returns the first where the time is in range or Nothing otherwise.
If matchingRange IsNot Nothing Then
lblRange.Text = String.Format("Between {0} and {1}",
matchingRange.Start,
matchingRange.End)
End If

Related

VB.NET get average from a range of values from a sortedlist (sortedlist.average)

I have a sortedlist like this;
public MeasuredValues as SortedList(Of DateTime, Double)
I throw in a bunch of values. For example;
MeasuredValues.add(New DateTime(2010, 1, 1),33)
MeasuredValues.add(New DateTime(2011, 1, 1),13)
MeasuredValues.add(New DateTime(2012, 1, 1),233)
MeasuredValues.add(New DateTime(2013, 1, 1),331)
MeasuredValues.add(New DateTime(2014, 1, 1),732)
MeasuredValues.add(New DateTime(2015, 1, 1),123)
Now I want to get the avarage of this values, say from 2011 to 2013. (ofcourse my real situation has much more values)
I've seen the sortedlist has a extension method called 'Avarage' ; https://msdn.microsoft.com/en-us/library/bb534965(v=vs.110).aspx
But I can't find any clear examples. I like VB.NET, but C# examples are also welcome...
I know I need to implement a function, but I don't know how. MSDN does not supply any example. Also, is this the best/fastest way to do it?, or is there a better alternative...
Thanks in advance...
Update:
I've tried this;
Dim MyAverage As Double = MeasuredValues.Average(Function(measure) CDate(measure.Key) >= ThisStepBeginTime And CDate(measure.Key) <= ThisStepEndTime)
But it only delivers a occasional -0,1
This 'one-line functions' are new for me, what am I doing wrong?
Update 2:
My example was a over simplefied example of the real problem. I'm trying to draw a graph, where every pixel represents a timespan. Like this;
For XCounter As Integer = 0 To MyBase.Width
Dim ThisStepBeginTime As DateTime = First.AddTicks(XCounter * TimeStep.Ticks)
Dim ThisStepEndTime As DateTime = First.AddTicks((XCounter + 1) * TimeStep.Ticks)
For Each MySerie In Me.AllSeries.Values
Dim MyAverage As Double = MySerie.Where(Function(measure) CDate(measure.Key) >= ThisStepBeginTime And CDate(measure.Key) <= ThisStepEndTime).Average(Function(measure) measure.Value)
e.Graphics.DrawLine(Pens.Red, XCounter, CInt((Me.Height / MySerie.HighestValue) * MyAverage), XCounter, 0)
Next
Next
This results in;
Sequence contains no elements
Because some of the steps don't have a value....
I think you can filter the list first and then get the average:
MeasuredValues _
.Where(Function(measure) cDate(measure.Key) >= dateFrom And cDate(measure.Key) <= dateTo) _
.Average(Function(measure) measure.Value)
REGARDING UPDATE 2:
If I understand the new issue corrently, you're getting an error on the Average if Where returns no elements. I know you can add .DefaultIfEmpty in between however I don't know how that would affect the Average function:
MeasuredValues _
.Where(Function(measure) cDate(measure.Key) >= dateFrom And cDate(measure.Key) <= dateTo) _
.DefaultIfEmpty() _
.Average(Function(measure) measure.Value)
I'm expecting the DefaultIfEmpty to return an empty element Of(DateTime, double) and thus averaging to 0

Check if date is between or equal to two other dates

I'm trying to check if a date is between two other dates. The two other dates are coming from two DatePickers formatted as dd/mm/yyyy. My code below works but if my searching date is i.e. equal to the from date I get a "Not between" message. If I search for date 17/05/2013 and I set the ranges to bet from: 17/05/2013 and to: 17/05/2013 I want to get a "Between" message. Any ideas?
Dim str As String = "srt_inlbp_20130517"
Dim sString As String
sString = str.Substring(str.Length - 8)
Dim dTableDate As Date = Date.ParseExact(str.Substring(str.Length - 8), "yyyyMMdd", Nothing)
Label9.Text = dTableDate
If ((dTableDate >= dFromDate.Value) And (dTableDate <= dToDate.Value)) Then
MsgBox("between")
Else
MsgBox("not between")
End If
I have rewritten your code in this testable format:
Dim str As String = "srt_inlbp_20130517"
Dim dTableDate As Date = _
Date.ParseExact(str.Substring(str.Length - 8), "yyyyMMdd", Nothing)
Dim dFromDate As New DateTime(2013, 5, 17)
Dim dToDate As New DateTime(2013, 6, 17)
If ((dTableDate >= dFromDate) And (dTableDate <= dToDate)) Then
Console.WriteLine("between")
Else
Console.WriteLine("not between")
End If
I get the result "between" so I can only suspect that your dFromDate.Value and/or dToDate.Value are not as you expect them to be. Can you check this please?
Try to write your comparators like you are reading a number line (e.g. always use a less-than sign).
Dim questionableDate As Date = New Date(2013, 05, 17)
Dim fromDate As Date = New Date(2013, 05, 17)
Dim toDate As Date = New Date(2013, 05, 17)
If (fromDate <= questionableDate) AndAlso (questionableDate <= toDate) Then
MsgBox("between")
Else
MsgBox("not between")
End If
You'll see that by using the number line approach you can easily determine what the code is doing. The from date and to date are at the ends with the questionable date sandwiched in the middle.
Note
If the code above does not wield the results you expect once you integrate it, then you will need to set some breakpoints and step through your code to see exactly what values your variables have.

Multiple True conditions in an IF statement in VB

Is it possible to have multiple conditions that can evaluate to true in an if statement? Primarily just shorthand to save some time:
Example:
if value = 1 or value = 9 or value = 3 or value = 17 Then return True
Im wondering if there is something to this effect (could not find in MSDN)
if value = 1,9,3,17 Then return True
Can't do that with an IF statement, but you could use:
SELECT CASE value
CASE 1, 3, 9, 17
' Do something
CASE 2, 4
' Do another thing
CASE ELSE
' Do something else
END SELECT
You can also try like:
If (New List(Of Integer)(New Integer() {1, 3, 5, 7, 9}).Contains(value)) Then
Return TRUE
End If
If it's a return statement, you could make it bit shorter like this;
Return value = 1 Or value = 9 Or value = 3 Or value = 17
Also if the values would be in an array, you could use Linq - Any function;
Dim value As Integer = 1
Dim values = New Integer() {1, 9, 3, 17}
Return values.Any(Function(number) number = value)
You can't do what you want exactly within VB, but you can get around it. Here is one method. Put your values into an Array. You can search the Array using the IndexOf method. If the IndexOf returns a number above -1, then the item was found in the array. There are some gotchas that you will want to read about on the MSDN page.
Dim value As Boolean
Dim myList() As Integer = {1, 9, 3, 17}
If Array.IndexOf(myList, 12) > -1 Then
value = True
Else
value = False
End If
Console.WriteLine("Found: {0}", value)
You can also shorten the test to an inline comparison and assignment, removing the need for the If statement above.:
value = (Array.IndexOf(myList, 12) > -1)

If date is (certain date) then

How would I make my application do an event when there is a certain date? I can't seem to find something that works. Year doesn't matter, just day and month is all I need.
Since day and month is all you want to match on:
Dim myDate As Date = Date.Now
Dim someMonth As Integer = 4
Dim someDay As Integer = 13
If myDate.Month = someMonth AndAlso myDate.Day = someDay Then
... month and day are matched
End If
Use IsDate....
If IsDate(MyDate) Then.....
Update various ways of defining date
'DateTime constructor: parameters year, month, day, hour, min, sec
Dim MyDate1 As New Date(2012, 12, 10, 12, 0, 0)
'initializes a new DateTime value
Dim MyDate2 As Date = #12/10/2012 12:00:52 AM#
'using properties
Dim MyDate3 As Date = Date.Now
Dim MyDate4 As Date = Date.UtcNow
Dim MyDate5 As Date = Date.Today
Try something like this:
Dim thisDate As Date = New Date(2014, 4, 13) ' Assuming this is provided
Dim certainDate As Date = New Date(2013, 4, 13) ' Assuming this is provided
If thisDate = New Date(thisDate.Date.Year, certainDate.Month, certainDate.Day) Then
Debug.Print("dates equal excluding year")
Else
Debug.Print("dates UNequal excluding year")
End If
Rememebr, this will always create a new date object for comparison but it works.
Hope it helps!

How can i retrieve date time available per second in one day?

my input is date.
But, i'm stuck on how to retrieve date time in every second.
I need to put the each second date time in the 2d array.so my array(0,0) should equal to 2/10/2014 00:00:00 AM and array(86399,0) is equal to 2/10/2014 23:59:59 PM.
i tried do looping as per below code:
Dim twoDarray(86399, 1) As String
Dim dtInput As Date
dtInput= #2/10/2014#
For i=0 to 86399
twoDarray(i, 0) = dtInput
dtInput = dtInput +second 'i know this not right
Next
I just don't know how to increase date time every second in right way.
Please help.
Have you thought about something along the lines of
Using a Datetime (MSDN Datetime)
dtInput= new DateTime(2014,10,2)
For i=0 to 86399
twoDarray(i, 0) = dtInput
dtInput = dtInput.AddSeconds(1)
Next
Or
dtInput= new DateTime(2014,10,2)
For i=0 to 86399
twoDarray(i, 0) = dtInput.AddSeconds(i+1)
Next
You can try following method also
Dim dtFrom As New DateTime(2014, 10, 2, 0, 0, 0)
Dim dtTo As New DateTime(2014, 10, 2, 23, 59, 59)
Dim iFirstDim As Integer = (dtTo - dtFrom).TotalSeconds
Dim iSecondDim As Integer = 10
Dim arrTime(iFirstDim, iSecondDim) As String
Dim i As Integer = 0
Do While (dtTo > dtFrom)
arrTime(i, 0) = dtFrom.ToString("d/MM/yyyy HH:mm:ss")
dtFrom = dtFrom.AddSeconds(1)
i += 1
Loop
HOW TO USE IT?
Dim dtResult As DateTime
If DateTime.TryParseExact(arrTime(150, 0), "d/MM/yyyy HH:mm:ss", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, dtResult) Then
MsgBox(dtResult.ToString("yyyy-MM-dd HH:mm:ss"))
End If