The program will know the time span if else vb.net - vb.net

I dont know how it is called thats why I called it time span.
I don't have any idea yet how to code it but this is what i want to do
Dim sy as String
If (June 2015) to (March 2016) Then
sy = "2015-2016"
End if
I know it is simple but i dont know how to code the June 2015 to 2016
Thanks in advance for the help
Edit :
Now i got to this code
I uses to do this
Dim value as DateTime = New DateTime(2017, 4, 1)
Dim value1 as DateTime = New DateTime(2018, 4, 1)
Dim sy as String
If my.computer.clock.localtime <= value then
sy = "2016-2017"
ElseIf my.computer.clock.localtime <= value1 then
sy = "2017-2018"
Else
msgbox("Check your current date")
End if
But when the computer's time changed to 2015 it shows "2016-2015"

So I use 4 textboxes to supply the data you need as variables. 2 for the years and 2 for the months. Also you need to think of how many moths left in the yeae and add the month number of the next year. If you span more than one year you have to account for this as well. O.K here is the snippet without error checking in a button event:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim firstÝear As Integer = CInt(TextBox3.Text)
Dim secondYear As Integer = CInt(TextBox4.Text)
Dim firstmonthnumber As Integer = CInt(TextBox5.Text) 'months number in first year
Dim secondmonthnumber As Integer = CInt(TextBox6.Text)
Dim d1 As DateTime = New DateTime(firstÝear, firstmonthnumber, 1)
Debug.Print(d1.ToString)
Dim d2 As DateTime = New DateTime(secondYear, secondmonthnumber, 1)
Debug.Print(d2.ToString)
Dim M As Integer = Math.Abs((d1.Year - d2.Year)) - 1
Debug.Print(M.ToString)
Dim myYear As Integer = 12 - firstmonthnumber 'month left to the end of first year
Dim months As Integer = ((M * 12) + Math.Abs((d1.Month - d2.Month))) + myYear
Debug.Print(months.ToString)
End Sub

Related

VB.Net find last day of month with date format

I am trying to find the last day of the month and compare it to today's date
I do NOT want the integer number I would like the result in this format "MM-dd-yyyy"
Date Picker will not work for this project
Here is the code I using but the process seems overly complicated concocting strings
Side note when today is after the 4th Tue I write True and the Last Day of the month to a DB
when today is after the last day of the month and the bool is now True I write the new last day of the new month and false to the DB
Function FourthTueOfMonth(dt As Date) As Date
Dim currDate = New Date(dt.Year, dt.Month, 1)
Dim nTuesday = 0
While nTuesday < 4
If currDate.DayOfWeek = DayOfWeek.Tuesday Then
nTuesday += 1
End If
currDate = currDate.AddDays(1)
End While
Return New Date(dt.Year, dt.Month, currDate.Day - 1)
End Function
Private Sub btnFindDate_Click(sender As Object, e As EventArgs) Handles btnFindDate.Click
Dim tORf As Boolean = False
Dim dateToday = Date.Today
Dim dateFourthTue = (FourthTueOfMonth(Date.Today))
tbFourthTue.Text = dateFourthTue.ToString("MMM-dd-yyyy")
tbThree.Text = dateFourthTue.ToString("yyyy-MM-dd")
tbEndOFMonth.Text = Date.DaysInMonth(Date.Now.Year, Date.Now.AddMonths(0).Month).ToString
Dim dToday As Date
dToday = Date.Parse("10-01-2021")
Dim dtY = dateToday.ToString("yyyy")
Dim dtM = dateToday.ToString("MM")
Dim eom As String = Date.DaysInMonth(Date.Now.Year, Date.Now.AddMonths(0).Month).ToString
Dim dtALL As String
dtALL = dtM & "-" & eom & "-" + dtY
Dim testD As Date
testD = Date.Parse(dtALL)
If tORf = False And dToday > dateFourthTue Then
MessageBox.Show("Today > Fourth Tue")
'tORf = True'Write True
'tbMessage.Text = tORf.ToString
End If
If tORf = True And dToday > testD Then
MessageBox.Show("Today > End Of Last Month")
'tORf = False write False
'tbMessage.Text = tORf.ToString
End If
End Sub
The solution provided by #Albert D. Kallal is great for Visual Basic since DateSerial is in the Visual Basic namespace in the DateAndTime class. Here is a solution that should work in both vb and C#.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dtToday As Date = Date.Today
Dim dtEndOfMonth = New Date(dtToday.Year, dtToday.Month + 1, 1).AddDays(-1)
Debug.Print(dtToday.ToString)
Debug.Print(dtEndOfMonth.ToString("MM-dd-yyyy"))
End Sub
A few things:
You want to use today - not "now()" as that includes a time portion. While a date type only has date, you should consider if you have datetime, and either way, no need to introduce and use a value that includes both date and time such as now does.
I reocmmend this code:
Dim dtToday As Date = Date.Today
Dim dtEndOfMonth As Date = DateSerial(dtToday.Year, dtToday.Month + 1, 0)
Debug.Print(dtToday)
Debug.Print(dtEndOfMonth)
Output:
Today happens to be the 1st, but any date would work. This includes end of year, and even leap years.
2021-10-01
2021-10-31
So, this is a long time old trick - goes back to old VB6, and even old VBA code from 20 years ago.
So, we use date serial to produce a date, but if you use 0 for the day, then you get the previous day, and thus gets you the last day of the current month.
So we toss in year, month + 1, and 0 for the date - that results in the last day of the current month.
I hate to admit I might have gave up the search too quick
found the answer here
Answer Here
Here is the code
Dim dateToday = Date.Now.AddMonths(0)
Dim dateEndOfMonth = New Date(dateToday.Year, dateToday.Month, DateTime.DaysInMonth(dateToday.Year, dateToday.Month))
tbMsg.Text = dateEndOfMonth.ToString("MM-dd-yyyy")
Code seems to be working ?
I have seen suggestions to use this format for comparing dates
TEST DATES use this format yyyyMMdd Please comment if you can add to the answer

Get same nth day of the month in x number of months

I am needing some help converting a function from access vba to vb.net.
The script generates a new date, based on the date entered, and the number of months to be added.
“If today is the second Tuesday in March, what will be the second Tuesday in 4 months?”
Public Function NdNwk(dType As String, _
dtSpan As Integer, sDate As Date) As Variant
' This Function RETURNS the DAY of WHICH WEEK
' (e.g. Second Tuesday of the Month).
' FUNCTIONS to be passed to Variables:
' gtDoW: Day of the WEEK of the START DATE.
' (1 for Sunday, 2 for Monday, etc.)
' gtWoM: WEEK of the MONTH of the START DATE.
' (1 for First, 2 for Second, etc.)
' gtDSTdt: Desired DATE
' (generated by the [DateAdd] Function).
' CALL EXAMPLE: If TODAY is Tuesday, March 10, 2020,
‘ (second Tuesday of March), then using
' NdNwk(m, 2, #5/21/2020#)
' Would generate the DATE 5/12/2020,
' As the SECOND TUESDAY of MAY.
Dim gtDSTdt As Date, gtWoM As Integer, gtDoW As Integer
Dim iLoop As Integer, iPick As Integer, dstDTdom As Date
gtDoW = Weekday(sDate)
gtWoM = (Int((Day(sDate) - 1) / 7) + 1)
gtDSTdt = DateAdd(dType, dtSpan, sDate)
For iLoop = 1 To Day(DateSerial(Year(gtDSTdt), _
Month(gtDSTdt) + 1, 0))
dstDTdom = DateSerial(Year(gtDSTdt), _
Month(gtDSTdt), iLoop)
If Weekday(dstDTdom, 1) = gtDoW Then
iPick = iPick + 1
If iPick = gtWoM Then
NdNwk = dstDTdom
Exit Function
End If
End If
Next
End Function
Any and all help is appreciated here.
I used several of the properties and methods of the .net DateTime structure. https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netcore-3.1
The arithmetic in the Function used the Mod operator which returns the remainder of the division. The integer division (the formard slash \) returns the integer portion of the division.
The only other thing that might be unfamiliar is the interpolated string, a string starting with $"". This allows you to directly embed variables in the string surround by { }.
Private Function NdNwk(InputDate As Date, MonthsAhead As Integer) As String
Dim newDate As Date
Dim DofWeek = InputDate.DayOfWeek
Dim Day = InputDate.Day
Dim OfInputMonth As Integer
If Day Mod 7 = 0 Then
OfInputMonth = Day \ 7
Else
OfInputMonth = (Day \ 7) + 1
End If
Dim TempDate = InputDate.AddMonths(MonthsAhead)
Dim NewMonth = TempDate.Month
Dim NewYear = TempDate.Year
Dim FirstWeek As Date
Dim NewDay As Integer
For d = 1 To 7
FirstWeek = New Date(TempDate.Year, TempDate.Month, d)
If FirstWeek.DayOfWeek = DofWeek Then
NewDay = d
Exit For
End If
Next
Dim DaysToAdd = (OfInputMonth - 1) * 7
newDate = New Date(NewYear, NewMonth, NewDay).AddDays(DaysToAdd)
Dim NewDateString = $"{newDate.ToString("MM/dd/yyyy")} is the {GetOrdinalString(OfInputMonth)} {DofWeek} of {TempDate.ToString("MMMM")}, {TempDate.Year}"
Return NewDateString
End Function
Private Function GetOrdinalString(input As Integer) As String
Dim output As String
Select Case input
Case 1
output = "1St"
Case 2
output = "2nd"
Case 3
output = "3rd"
Case 4
output = "4th"
Case 5
output = "5th"
Case Else
output = ""
End Select
Return output
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim InputDate As Date
Dim MonthsToAdd As Integer
If Not Date.TryParse(TextBox1.Text, InputDate) Then
MessageBox.Show("Please enter a valid date in Date")
Return
End If
If Not Integer.TryParse(TextBox2.Text, MonthsToAdd) Then
MessageBox.Show("Please enter a valid number in Months To Add")
Return
End If
Dim d = NdNwk(InputDate, MonthsToAdd)
MessageBox.Show(d)
End Sub
First of all, thanks for all the feedback.
The solution that I was able to parse together is as follows:
A text box to show the number of months.
A text box to show the new date.
A button click action to run the following code:
Private Sub BtnMonth_Click(sender As Object, e As EventArgs) Handles BtnMonth.Click
Dim WrkDt As Date = Now
Dim QtyMnths As Integer = CType(TxtMntCount.Text, Int32)
Dim newFoM = New Date(WrkDt.Year, WrkDt.Month, 1).AddMonths(QtyMnths)
Dim DoWDt As Integer = WrkDt.DayOfWeek
Dim newMntdate = newFoM.AddDays(Enumerable.Range(0,
Date.DaysInMonth(newFoM.Year, newFoM.Month) - 1).Where(Function(i) newFoM.AddDays(i).DayOfWeek = DoWDt).Skip(1).First())
TxtNewDate.Text = Format(newMntdate, "MMMM dd, yyyy (ddd)")
End Sub
This works perfectly fine for me!
Mary's solution looks great, and I will give it a shot in the future when I need a modular input.
Thanks again for all the help!
I tested your solution, and it doesn’t produce the described results.
See test and correct solution at: https://dotnetfiddle.net/v5wGng
A couple of things from your original problem, you should prefer calculation to loops wherever possible, and you should use the required types wherever possible. If you have date in one format (string) and need it in another for your calculations, you should do the conversion and then call a function that does your calculations where all of the parameters are of the correct type.
Public Function GetSameWeekAndWeekDay(dt as date, months as integer) as Date
Dim newMonth =(new date(dt.year, dt.month, 1)).AddMonths(Months)
Dim week = getweek(dt)
Dim sameWeekDay = GetNthDayOfWeek(newMonth, week, dt.DayOfWeek)
Return SameWeekday
End Function
Public Function GetWeek(dt as date) as integer
Return(dt.day - 1) \ 7
End Function
Public Function GetNthDayOfWeek(dt as date, week as integer, weekDay as System.DayofWeek) as Date
Dim first = new Date(dt.year, dt.month, 1)
Dim baseDate = first.AddDays(-(first.DayOfWeek - system.dayofweek.Sunday))
Dim newDate = baseDate.AddDays((week * 7) + weekday)
If(newdate.DayOfWeek < first.DayOfWeek) then
newDate = newDate.AddDays(7)
End If
Return newdate
End Function

How to calculate how many days until someone will turn 18 using their date of birth in VB?

For a computer science assignment I need to calculate how many days it will be until the user turns 18, using their date of birth.
Dim dateToday As Date = Date.Today()
Dim ageNow As Integer = dateToday.Subtract(birthDate).Days
' 6750 is 365 * 18
Dim daysEighteen As Integer = 6750 - ageNow
MsgBox("You will be 18 in " & daysEighteen)
This is the code I have at the moment, however when tested it doesn't come up with the correct output.
This isn't the entire code but I have just included the necessary lines for this part of the program.
Thanks in advance.
I would use a different method. Add 18 years to the birthdate and then subtract the today date. This should avoid the error implicit in your calculation (365*18 doesn't count the leap years)
Dim birthDate = New DateTime(1999,1,1)
Dim adultDate = birthDate.AddYears(18)
Console.WriteLine(adultDate.ToString("MM/dd/yyyy"))
Dim daysLeft = adultDate.Subtract(DateTime.Today).Days
Console.WriteLine(daysLeft)
This is the finished program, with commenting.
Public Class Form
Private Sub btnEnter_Click(sender As System.Object, e As System.EventArgs) Handles btnEnter.Click
' Stores the textboxes as variables
Dim name As String = txtName.Text
Dim birthDate As Date = dtpBirthDate.Text
Dim electionDate As Date = dtpElectionDate.Text
' This is the age the user will be on the date of the election
Dim ageElection As Integer = electionDate.Subtract(birthDate).Days
' If the user is 18 or older, it outputs that they are. If they're not, it calculates how many days
' it will be until they are and displays it.
If (ageElection / 365) > 18 Then
' Outputs that the user is 18 or older
MsgBox("You are 18 or older!")
Else
' This is when the user will turn 18
Dim adultDate As Date = birthDate.AddYears(18)
' This calculates how many days it will be until the user is 18, using when they turn 18
Dim daysLeft = adultDate.Subtract(DateTime.Today).Days
' Outputs that the user is younger than 18 and outputs how many days until they're 18
MsgBox("You are younger than 18! You will be 18 in " & daysLeft)
End If
End Sub
End Class

How to add 1 month to selected DateTimePicker

I'm having an issue with DateTimePicker.
What I am currently trying to do is based off of what text is in lblPrevSem(Previous Semester), which is getting its selection from a drop down on a previous screen, i want to add a certain amount of time to the DateTimePicker.
Public Property CustomFormat As String
Dim SemesterMonths As Integer
Dim SemesterDays As Integer
Private Sub DeptCreatePrevSch_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim SemesterYear() As String = DeptPrevSch.CboSem.Text.Split(",")
lblPrevSem.Text = SemesterYear(0)
cboYear.Text = Date.Now.Year
For i As Integer = 0 To 5
cboYear.Items.Add(Date.Now.Year + i)
cboYear.SelectedIndex = 0
Next
If InStr(lblPrevSem.Text, "Fall") Then
SemesterMonths = 1
ElseIf InStr(lblPrevSem.Text, "Spring") Then
SemesterMonths = 1
ElseIf InStr(lblPrevSem.Text, "Summer") Then
SemesterDays = 14
End If
Call dtpStart_ValueChanged(sender, e)
End Sub
Private Sub dtpStart_ValueChanged(sender As Object, e As EventArgs) Handles dtpStart.ValueChanged
Dim StartDate As Date
Dim StartStringDate As String
Dim EndDate As Date
Dim EndStringDate As String
dtpStart.Format = DateTimePickerFormat.Custom
dtpStart.CustomFormat = "MMMM dd, yyyy dddd"
StartDate = dtpStart.Value.ToString
StartStringDate = StartDate.ToString("MMMM dd, yyyy dddd")
lblRegStartDate.Text = StartStringDate
EndDate = dtpStart.Value.AddMonths(SemesterMonths)
EndDate = dtpStart.Value.AddDays(SemesterDays)
EndStringDate = EndDate.ToString("MMMM dd, yyyy dddd")
lblRegEndDate.Text = EndStringDate
End Sub
I can get it to add in days just fine but when ever i try and add in 1 month, it doesn't seem to work at all.
I've tried multiple different ways to add in a 1 month but nothing so far has worked. The closet ive been was adding in 30 days but then that doesn't account for months that have 31 days.
Reg Start Date is what ever the DateTimePicker is and Reg End Date should be the added days based off of what lblPrevSem is
Both Reg Start/End Date are displayed as labels
(i.e. Fall = 1 Month, Spring = 1 Month, Summer = 2 Weeks)
Your problem is that you are resetting the value for EndDate after adding the SemesterMonths value. You should add the SemesterDays value to the EndDate variable, not reset the value of EndDate with dtpStart.Value.AddDays(SemesterDays):
EndDate = dtpStart.Value.AddMonths(SemesterMonths)
EndDate = EndDate.AddDays(SemesterDays)
Just get the datetimepicker value and put .AddYears(0) or .AddDays(0) or AddMonths(0) behind it.
But you can also use them all at the same time.
nextServiceDateTimePicker.Value.AddYears(0).AddDays(0).AddMonths(0);
Just replace the 0 with lets say i and give it the value you need it to be.

How to add a table from toolbox and write vb.Net code in visual studio 2012 express

I am learning VB.net. I am following Charpter 3 of Brian Siler's special edition (2001) using MS VB.net. It looks thing has been changed not too much with VB, but I met a problem in adding table from toolbox.
In the Toolbox (versions from Visual Studio 2012 Express; ASP.net 2012), to build a VB.net project, there are items like TextBox and Table. To build a web app, I can add TextBox, Label, etc and coding them without problems. However, when I add table, there is a problem.
As with Textbox and Label, I rename the table ID (to tblAmortize) first. Then I input the codes from their book, and got an error:
'tblAmortize' is not declared. It may be inaccessible due to its protection level"
As I know, the TextBox item, such as txtPrincipal.Text does not need to be declared when we use it. But it seem this "table" tblAmortize item needs to be declared first, or needs to be build up a link because tblAmortize is located in Form 2 while btnShowDetail_Click is in Form 1. The full code is as following:
Public Class Hello_Web
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim intTerm As Integer 'Term, in years
Dim decPrincipal As Decimal 'Principal amount $
Dim decIntRate As Decimal 'Interst rate %
Dim dblPayment As Double 'Monthly payment $
Dim decMonthInterest As Decimal 'Interest part of monthly payment
Dim decTotalInterest As Decimal = 0 'Total interest paid
Dim decMonthPrincipal As Decimal 'Principal part of monthly pament
Dim decTotalPrincipal As Decimal = 0 'Remaining principal
Dim intMonth As Integer 'Current month
Dim intNumPayments As Integer 'Number of monthly payments
Dim i As Integer 'Temporary loop counter
Dim rowTemp As TableRow 'Temporary row object
Dim celTemp As TableCell 'Temporary cell object
If Not IsPostBack Then 'Evals true first time browser hits the page
'SET Up THE TABLE HEADER ROW
rowTemp = New TableRow()
For i = 0 To 4
celTemp = New TableCell()
rowTemp.Cells.Add(celTemp)
celTemp = Nothing
Next
rowTemp.Cells(0).Text = "Payment"
rowTemp.Cells(1).Text = "Interest"
rowTemp.Cells(2).Text = "Principal"
rowTemp.Cells(3).Text = "Total Int."
rowTemp.Cells(4).Text = "Balance"
rowTemp.Font.Bold = True
tblAmortize.Rows.Add(rowTemp)
'PULL VALUES FROM SESSION VARIABLES
intTerm = Convert.ToInt32(Session("term"))
decPrincipal = Convert.ToDecimal(Session("Principal"))
decIntRate = Convert.ToDecimal(Session("IntRate"))
dblPayment = Convert.ToDecimal(Session("decPayment"))
'CALCULATE AMORTIZATION SCHEDULE
intNumPayments = intTerm * 12
decTotalPrincipal = decPrincipal
For intMonth = 1 To intNumPayments
'Determine Values For the Current Row
decMonthInterest = (decIntRate / 100) / 12 * decTotalPrincipal
decTotalInterest = decTotalInterest + decMonthInterest
decMonthPrincipal = Convert.ToDecimal(dblPayment) - decMonthInterest
If decMonthPrincipal > decPrincipal Then
decMonthPrincipal = decPrincipal
End If
decTotalPrincipal = decTotalPrincipal - decMonthPrincipal
'Add the values to the table
rowTemp = New TableRow()
For i = 0 To 4
celTemp = New TableCell()
rowTemp.Cells.Add(celTemp)
celTemp = Nothing
Next i
rowTemp.Cells(0).Text = intMonth.ToString
rowTemp.Cells(1).Text = Format(decMonthInterest, "$###0.00")
rowTemp.Cells(2).Text = Format(decMonthPrincipal, "$###0.00")
rowTemp.Cells(3).Text = Format(decTotalInterest, "$###0.00")
rowTemp.Cells(4).Text = Format(decTotalPrincipal, "$###0.00")
tblAmortize.Rows.Add(rowTemp)
rowTemp = Nothing
'PrevFormat()
Next intMonth
End If
End Sub
Protected Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim decPrincipal As Decimal
Dim decIntRate As Decimal
Dim intTerm As Integer, dblPayment As Double
'Store the principle in the variable decprincipal
'decPrincipal = CDbl(txtPrincipal.Text)
decPrincipal = (txtPrincipal.Text)
'Convert interest rate to its decimal equivalent
' i.e. 12.75 becomes 0.1275
decIntRate = CDbl(txtIntrate.Text) / 100
'Convert annual interest rate to monthly
' by dividing by 12 (months in a year)
decIntRate = decIntRate / 12
'Convert number of years to number of months
' by multiplying by 12 (months in a year)
intTerm = CDbl(txtTerm.Text) * 12
'Calculate and display the monthly payment.
' The format function makes the displayed number look good.
dblPayment = decPrincipal * (decIntRate / (1 - (1 + decIntRate) ^ -intTerm))
txtPayment.Text = Format(dblPayment, "$#,##0.00")
'Add Amortization Schedule
' The Schedule button will be shown only after you click the Calculate Payment LinkButton
btnShowDetail.Visible = True
End Sub
Protected Sub btnShowDetail_Click(sender As Object, e As EventArgs) Handles btnShowDetail.Click
'Storetext box values in session variables
Session.Add("Principal", txtPrincipal.Text)
Session.Add("IntRate", txtIntrate.Text)
Session.Add("Term", txtTerm.Text)
Session.Add("Payment", txtPayment.Text)
'Display the Amortization form
Response.Redirect("frmAmort.aspx")
End Sub
End Class
While you declare the table you must write runat = "Server"
This is the code sample
<Table ID = "tblMyTable" runat = "Server">
.
.
.
</Table>
Now you can use your table in code.
If you can already access the table in Form2's Code and you want it to be accessed in Form1's Code and if you don't know how to do it then here is the solution :
Dim tbl as new Table
tbl = CType(Form1.FindControl("tblMyTable"),Table)