!ArgumentOutofRangeException was unhandled - vb.net

The added or subtracted value results in un-representable Date Time. Parameter name:T
Dim offset = New Date(1, 1, 1)
Dim dateOne = dtpbdate.Value
Dim dateTwo = Date.Now
Dim diff As TimeSpan = dateTwo - dateOne
Dim years = (offset + diff).Year - 1
If years < 18 And years < 50 Then
MsgBox("Age requirement must be 18 - 50 years old!")
Else
txtage.Text = years.ToString
End If

Related

vb.net find 4th Wednesday of month with visual basic

I am trying to find the fourth Wednesday of the current Month and Year when a form loads
I have converted numerous C# code to Visual Basic with no results
Would someone explain what is wrong with this code OR explain how to accomplish this in VB Code
Private Sub SurroundingSub()
Dim thisDate As Date = Today
tbMonth.Text = thisDate.ToString("MMMM")
tbYear.Text = thisDate.ToString("yyyy")
Dim month As Integer
month = tbMonth.Text
Dim year As Integer
year = tbYear.Text
Dim fourthWed As Date = New Date(year, month, 4)
tbFour.Text = fourthWed.ToLongDateString
While fourthWed.DayOfWeek <> DayOfWeek.Wednesday
fourthWed = fourthWed.AddDays(1)
tbFour.Text = fourthWed.ToShortDateString
End While
End Sub
This is a JavaFX statement that I am trying to implement in VB.Net
if(TorF.equals("F") && today.isAfter(fourthTUEofMONTH))
This sets the date
public void setDATES() throws IOException, SQLException{
today = LocalDate.now();
fourthTUEofMONTH = LocalDate.now();
fourthTUEofMONTH = fourthTUEofMONTH.with(TemporalAdjusters.dayOfWeekInMonth(4, DayOfWeek.TUESDAY));
endMONTH = LocalDate.now();
endMONTH = endMONTH.with(TemporalAdjusters.lastDayOfMonth());
}
For a more general solution, with my function you can easily find the first, second, third, forth or fifth sunday, monday, tuesday, wednesday or whatever you want:
Public Function GetXDayOfWeek(Day As DateTime,
DayOfWeek As DayOfWeek,
Optional Index As Integer = 1) As DateTime
Dim First As New Date(Day.Year, Day.Month, 1)
Dim Diff As Integer = (DayOfWeek - First.DayOfWeek + 7) Mod 7
Return First.AddDays(Diff + (Index - 1) * 7)
End Function
So if you want to find the forth wednesday of the current month, use it like:
Dim DateToFind As DateTime = GetXDayOfWeek(Today, DayOfWeek.Wednesday, 4)
Your while statement will stop on the first Wednesday it finds, not the fourth. Keep track of the number of Wednesdays you encounter as you iterate and once you find the fourth then you can update tbFour.
Also as mentioned in the comments you'll want to start at the first day of the year.
Dim fourthWed As Date = New Date(year, month, 1)
Dim wednesdayCursor As Integer = 0
While wednesdayCursor < 4
If fourthWed.DayOfWeek = DayOfWeek.Wednesday Then
wednesdayCursor += 1
End If
fourthWed = fourthWed.AddDays(1)
End While
'Subtract one day because we added one on loop:
fbFour.Text = fourthWed.AddDays(-1).ToShortDateString()
You should make the function of getting the fourth Wednesday into a separate method, perhaps generalizing it for any day of the week, but just for the fourth Wednesday...
Module Module1
Function FourthWedOfMonth(dt As DateTime) As Integer
Dim currDate = New DateTime(dt.Year, dt.Month, 1)
Dim nWednesdays = 0
While nWednesdays < 4
If currDate.DayOfWeek = DayOfWeek.Wednesday Then
nWednesdays += 1
End If
currDate = currDate.AddDays(1)
End While
Return currDate.Day - 1
End Function
Sub Main()
For mo = 1 To 12
Console.Write(FourthWedOfMonth(New DateTime(2020, mo, 17)) & " ")
Next
Console.ReadLine()
End Sub
End Module
Outputs the correct days for 2020:
22 26 25 22 27 24 22 26 23 28 25 23
If you wanted the DateTime of the fourth Wednesday, you could
Function FourthWedOfMonth(dt As DateTime) As DateTime
Dim currDate = New DateTime(dt.Year, dt.Month, 1)
Dim nWednesdays = 0
While nWednesdays < 4
If currDate.DayOfWeek = DayOfWeek.Wednesday Then
nWednesdays += 1
End If
currDate = currDate.AddDays(1)
End While
Return New DateTime(dt.Year, dt.Month, currDate.Day - 1)
End Function
and then Console.WriteLine(FourthWedOfMonth(DateTime.Today).ToString("dd-MMM-yyyy")) would output "22-Jul-2020" (at the time of writing).
I'd find the fourth Wednesday of the current month this way:
Private Sub FourthWednesdayOfCurrentMonth()
Dim firstOfMonth As DateTime = DateTime.Today.AddDays(-1 * (DateTime.Today.Day - 1))
Dim firstWednesday As DateTime = firstOfMonth.AddDays((7 + (DayOfWeek.Wednesday - firstOfMonth.DayOfWeek)) Mod 7)
Dim fourthWednesday As DateTime = firstWednesday.AddDays(21)
tbYear.Text = fourthWednesday.Year
tbMonth.Text = fourthWednesday.Month
tbFour.Text = fourthWednesday.Day
End Sub
Written generically for any day of the week, that would change to:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fourthWednesday As DateTime = FourthWeekDayOfCurrentMonth(DayOfWeek.Wednesday)
tbYear.Text = fourthWednesday.Year
tbMonth.Text = fourthWednesday.Month
tbFour.Text = fourthWednesday.Day
End Sub
Private Function FourthWeekDayOfCurrentMonth(ByVal WeekDay As DayOfWeek) As DateTime
Dim firstOfMonth As DateTime = DateTime.Today.AddDays(-1 * (DateTime.Today.Day - 1))
Dim firstWeekday As DateTime = firstOfMonth.AddDays((7 + (WeekDay - firstOfMonth.DayOfWeek)) Mod 7)
Return firstWeekday.AddDays(21)
End Function

Arithmetic operation resulted in an overflow - Vb.Net

Hi I am getting the following error when computing GMT Time using nanoseconds as a long.
System.OverflowException: 'Arithmetic operation resulted in an overflow.'
Is there another data type that would work better with big values?
Private Sub gmtime(ByVal iSeconds As Object, ByVal iNanoseconds As Long, ByRef Timestamp As String)
Dim time As Object
Dim islpyr, lpcnt As Long
Dim t As Object
Dim i As Object
Dim ystart As Long
Dim y As Long
Dim sph As Object 'seconds per hour
Dim spd As Object 'seconds per day
Dim spy As Object 'seconds per year
Dim tm_sec As Long
Dim tm_min As Long
Dim tm_hour As Long
Dim tm_mday As Long
Dim tm_mon As Long
Dim tm_year As Long
Dim tm_wday As Long
Dim tm_yday As Long
Dim tm_isdst As Long
Dim mons(11) As Long
Dim temp As Object
Dim iMicroSeconds As Long
Dim iZeroCount As Long
Dim strZero As String
Dim strMicro As String
Dim iMicroData As Long
mons(0) = 31
mons(1) = 28
mons(2) = 31
mons(3) = 30
mons(4) = 31
mons(5) = 30
mons(6) = 31
mons(7) = 31
mons(8) = 30
mons(9) = 31
mons(10) = 30
mons(11) = 31
sph = CDec(60 * 60)
spd = CDec(24 * sph)
spy = CDec(365 * spd + 6 * sph) 'a year is about 365.25 days
tm_isdst = 0
time = CDec(iSeconds)
If time < 0 Then
time = time * (-1)
End If
i = CDec(time)
i = Fix(i / spd) Mod 7 + 4
While i >= 7
i = i - 7
End While
tm_wday = i
temp = Fix(time / spd)
temp = temp * spd
i = time - temp
tm_hour = Fix(i / sph) Mod 24
tm_min = Fix(i / 60) Mod 60
tm_sec = i Mod 60
y = Fix(time / spy)
y = y + 370
time = Fix(time / spd)
Do
islpyr = 0
If ((y Mod 4) = 0) And (((y Mod 100) <> 0) Or ((y Mod 400) = 0)) Then
islpyr = 1
End If
lpcnt = Fix(y / 4)
lpcnt = lpcnt - Fix(y / 100)
lpcnt = lpcnt + Fix(y / 400)
lpcnt = lpcnt - 89
ystart = (y - 370) * 365 + lpcnt
If ystart > time Then
y = y - 1
End If
Loop While ystart > time
time = time - ystart
If time = 365 Then
time = 0
y = y + 1
End If
If islpyr Then
time = time + 1
End If
tm_yday = time
time = time + 1
For i = 0 To 10
t = mons(i)
If (i = 1) And (islpyr = 1) Then
t = t + 1
End If
If time <= t Then
Exit For
End If
time = time - t
Next i
tm_year = y - 300 + 1900
tm_mon = i + 1
tm_mday = time
strZero = "."
iZeroCount = 6
iMicroSeconds = Fix(iNanoseconds / 1000)
iMicroData = iMicroSeconds
While iMicroSeconds <> 0
iMicroSeconds = Fix(iMicroSeconds / 10)
If (iMicroData Mod 10) = 0 Then
iMicroData = iMicroSeconds
End If
If iZeroCount <> 0 Then
iZeroCount = iZeroCount - 1
End If
End While
For i = 1 To iZeroCount
strZero = strZero + "0"
Next i
If Fix(iNanoseconds / 1000) <> 0 Then
strMicro = strZero + CStr(Fix(iNanoseconds / 1000))
Else
strMicro = strZero
End If
Timestamp = CStr(tm_year) + "-" + CStr(tm_mon) + "-" + CStr(tm_mday) + " " + CStr(tm_hour) + ":" + CStr(tm_min) + ":" + CStr(tm_sec) + strMicro
End Sub
It wouldn't let me add the code as the post is mostly code. The nanoseconds values are coming from a waveform file and this function is used to process it into GMT time.
The function is called on a loop for each line of the file and returns this error mid-way through the loop.
The value is '1.5518651852110167E+270' when it hits the error
I'm sorry but there's no way to put a 10^270 number inside ANY variable.
The biggest variable for numbers is Long that holds:
signed 64-bit (8-byte) integers ranging in value from
-9,223,372,036,854,775,808 through 9,223,372,036,854,775,807
(9.2...E+18).
From Long DataType
I sueggest you to avoiding counting time in nanoseconds instead use seconds, minutes, or even days if your TimeSpan is too big.
Counting time in nanoseconds is pointless.
Remarks
If you couldn't avoid using nanoseconds because your file is in nanoseconds your only option is to convert you nanoseconds value in a DateTime format on every line and hope that the value will be shorter than 9.2E+18
Otherwise you could use a BigInteger and use it to calculate a DateTime for every line of your file.
Just for the curiosity: You would need a 896 bytes unsigned DataType to store a 1.5*10^270 inside it.

if statement to mathematical addition gives answer zero in vb.net

' total service till retirement
retirement = Me.DateTimePicker2.Value
appointment = Me.DateTimePicker1.Value
Dim workingTime As TimeSpan = retirement - appointment
Dim yearVal As Double = workingTime.TotalDays / 365
Dim years = CInt(Math.Floor(yearVal))
Dim monthVal = (workingTime.TotalDays - years * 365) / 30
Dim months As Int32 = CInt(Math.Floor(monthVal))
Dim dayVal = workingTime.TotalDays - (years * 365 + months * 30)
Dim days As Int32 = CInt(Math.Floor(dayVal))
Dim result = $" {years} years {months} months & {days} Days"
tservice.Clear()
tservice.Text = result
' Pay reckonable for pension.
reckonable = Val(lastpay.Text) + Val(increment.Text)
'17. Service on the date of retirement. rounded off
If months > 5 Then
totalyear = (Val(years) + 1)
End If
'1. PENSION:-17760x26x7/300=Rs. 10774.40
tpension.Clear()
pension = (Val(reckonable) * Val(totalyear) * 7 / 300)
tpension.Text = pension
i need that answer should not be zero but due to totalyear a integer variable inside if statement gives zero i want it to add a value 1 if num of months is greater than 5 kindly help me.

age calculation in vb.net coding

net coding and i am really stuck in this basic age calculation. I have created a form field and in a groupbox it should display the age of a person. The biggest problem i am facing with the code is factoring in the month. I have tried all types such as using DateInterval.Month but still no luck. Here MyEntPatient.DOB is the DOB of patient
Dim Years As Integer
Dim BDAY As New DateTime(Now.Year)
BDAY = MyEntPatient.DOB
If (BDAY > Now) Then
Years = DateDiff(DateInterval.Year, MyEntPatient.DOB, Now) - 1
Else
Years = DateDiff(DateInterval.Year, MyEntPatient.DOB, Now)
End If
Me.gpxPatientDetails.Text = " Age:" + Years.ToString()
I think you want to have the difference of the date, I think this example help you:
Dim birthday As New DateTime(12, 12, 2012)
Dim difference As DateTime = DateTime.Now - birthday
Dim years As Integer = difference.Years
If you have problem with bigger/smaller age, because someone doesn't have a birthday this year (born in December for example), you can try this:
Dim bday As New DateTime(2010, 1, 25)
Dim months As Integer = DateDiff(DateInterval.Month, bday, Now)
Dim years As Integer = months / 12
Function AgeCalculator(ByVal FromDate As String, Optional flgyearOnly As Boolean = False) As String '23/11/2017
If Not IsDate(FromDate) Then Return ""
Dim tmpYear As String = "", tmpMonth As String = "", tmpdiff As Integer = 0
Dim tmpAge As String = ""
tmpdiff = DateDiff(DateInterval.Day, CDate(Format2DateMMM(FromDate)), Now)
If tmpdiff <= 0 Then Return ""
If tmpdiff > 0 And tmpdiff <= 29 Then
Return tmpdiff & " Days"
End If
If tmpdiff = 30 Then
Return " 1 Month"
End If
tmpYear = tmpdiff / 365
If InStr(tmpYear, ".") > 0 Then
tmpYear = Microsoft.VisualBasic.Left(tmpYear, InStr(tmpYear, ".") - 1)
End If
If Val(tmpYear) = 0 Then tmpYear = ""
If Val(tmpYear) > 0 Then
tmpAge = tmpYear & " years"
If flgyearOnly Then Return tmpAge
End If
tmpdiff = (tmpdiff - (Val(tmpYear) * 365))
tmpMonth = tmpdiff / 30
If InStr(tmpMonth, ".") > 0 Then
tmpMonth = Microsoft.VisualBasic.Left(tmpMonth, InStr(tmpMonth, ".") - 1)
End If
If Val(tmpMonth) = 0 Then tmpMonth = ""
If tmpMonth > 0 Then
tmpAge &= " " & tmpMonth & " Months"
End If
tmpdiff = (tmpdiff - (Val(tmpMonth) * 30))
If Val(tmpdiff) > 0 Then
tmpAge &= " " & tmpdiff & " Days"
End If
Return tmpAge: End Function
A bit old posting, but the question is not!
Typically the 'age' is the whole years completed:
Dim DOB As Date = DateValue("1970-10-28")
Dim Tday As Date = DateValue("2022-02-21")
Console.WriteLine(
Int((CInt(Tday.ToString("yyyyMMdd")) - CInt(DOB.ToString("yyyyMMdd"))) / 10000)
)

Special date formatted string to Date (VB.net)

If i have a string containing a date formatted like this:
1402-3
which means Year: 2014, Week: 02 and Day number 3 (monday is 1), how can i convert this to a normal date? (in this case the date above is today; 2014-01-08 - wednesday 8 jan 2014)
Edit: I came up with a function like this, can anyone tell if this is gonna fail or maybe have a better and better coded function/solution?
Private Function StrangeFormattedDateToRegularDate(ByVal StrangeDate As String) As Date
Dim Y As String = "20" & StrangeDate.Substring(0, 2) 'I'll be dead before this fails, haters gonna hate
Dim W As String = StrangeDate.Substring(2, 2)
Dim D As String = StrangeDate.Substring(5, 1)
'Get first day of this year
Dim RefDate As Date = New Date(CInt(Y), 1, 1)
'Get the first day of this week (can be the year before)
Dim daysOffSet As Integer = DayOfWeek.Monday - RefDate.DayOfWeek
RefDate = RefDate.AddDays(daysOffSet)
'Add as many days as the weeks is
RefDate = RefDate.AddDays(7 * CInt(W))
'now the date is the last day of this week (plus one day), remove the days that are ahead, and remove that extra day
Dim daysToRemove = ((7 - CInt(D)) * -1) - 1
RefDate = RefDate.AddDays(daysToRemove)
Return RefDate
End Function
This should be what you're looking for :) This looked challenging so I tried it. Tell me if it works for you or not :)
Function GetDate(InputDate As String) As DateTime
Dim FirstDayofYear As Date = CType("1/1/20" & Mid(InputDate, 1, 2), Date)
Dim LastDayofYear As Date = CType("12/31/20" & Mid(InputDate, 1, 2), Date)
Dim target As Date
For x = 0 To DateDiff(DateInterval.Day, FirstDayofYear, LastDayofYear)
Dim dfi = DateTimeFormatInfo.CurrentInfo
Dim calendar = dfi.Calendar
Dim weekOfyear = calendar.GetWeekOfYear(FirstDayofYear.AddDays(x), dfi.CalendarWeekRule, DayOfWeek.Sunday)
If CInt(Mid(InputDate, 3, 2)) = weekOfyear And CInt(Mid(InputDate, InStr(InputDate, "-") + 1)) = FirstDayofYear.AddDays(x).DayOfWeek Then
target = FirstDayofYear.AddDays(x)
GoTo skip
End If
Next x
skip:
Return target
End Function
This works up to Year 2099. We're probably all dead by then.