Find the day given date and number of days - vb.net

Am looking a function that would aid me to auto detect due date when duration period number is entered in duration textbox.Am having challenge since all the months do not end with same date number i.e. 31 as some end on 30.
NOTE: The function should be able to automatically calculate up to next year if lets say user inputs 3 while in November 2018 its means the duration period will go up January 2019
See the picture below
Dim start_date As Date = dtpStart.Value
Dim totalDays As Integer = 3 * 30
Dim ts As TimeSpan = start_date.Add(totalDays)
Dim end_date As Date = ts
I have tried the above but its giving me an error "value of type integer can not be converted to system.TimeSpan."

If i understand you correctly, if a user enters 3 you want to advance 3 times 30 days later from the start_date.
Dim start_date = dtpStart.Value
Dim end_date = start_date.AddDays(3* 30)
In terms of a function, you could have:
private function AddDays(Byval start_date as Date, Byval amount as integer) as Date
Dim end_date = start_date.AddDays(amount)
return end_date
end function
The usage would be:
Dim new_date = AddDays(dtpStart.Value, 3*30)

Related

Calculate difference in month and years between two date in vb.net

i have a question for you, my first one. Im trying to calculate the difference in years and months between 2 dates using vb.net. I'm just started working with vb and im new to programming, so i might sound really dumb. This is my expected output:
date1 1/6/2015 date2 1/1/2019 3 years 7 months and so on.
if date2 is < than data1 then the program should return a negative value in months/years. day number are irrelevant, i just want to know how many months/years.
This is the code that i found and it works if data1 is > than data2 but doesn't if data2 is > than data1.
Dim data1 As DateTime = ("1/3/2021") # working examples
Dim data2 As DateTime = ("1/5/2022")
Public Shared Function GetDateSpanText(fromDate As DateTime, toDate As DateTime) As String
Dim years As Integer = 0, months As Integer = 0, days As Integer = 0
Do Until toDate.AddYears(-1) < fromDate
years += 1
toDate = toDate.AddYears(-1)
Loop
Do Until toDate.AddMonths(-1) < fromDate
months += 1
toDate = toDate.AddMonths(-1)
Loop
Do Until toDate.AddDays(-1) < fromDate
days += 1
toDate = toDate.AddDays(-1)
Loop
Return String.Format("{0} Year(s) {1} Month(s) {2} Day(s)", years, months, days)
End Function
how can i make it work the other way? there are functions that can do this?
thanks to everyone
The simplest way to deal with dates and time intervals is using the TimeSpan struct.
Take a look at this snippet:
Sub Test()
Dim startDate As New Date(2022, 8, 17)
Dim endDate As New Date(2023, 10, 15)
Dim timeBetween As TimeSpan = endDate - startDate ' TimeSpan objects represents a time interval
Dim yearsBetween As Double = timeBetween.TotalDays / 365
Dim monthsBetween As Double = yearsBetween * 12
' Try using simplified string interpolation, like this:
Console.WriteLine($"Years between: {yearsBetween}; months between: {monthsBetween}") ' Note the $ sign at string beginning
End Sub
Using TimeSpan is conveninent because it gives you access to wathever time fraction you want to use:
timeBetween.TotalDays ' Represents the whole time interval in days (double)
timeBetween.TotalHours ' Represent the whole time interval in hours (double)
timeBetween.Days ' Represents the days part only (integer)
As you may guess, you need to substract the oldest date from the newest date to get a positive TimeSpan.
Note: the TimeSpan struct can not provide you .TotalMonths or .TotalYears methods because months and years are not always of the same length (months can vary between 28 and 31 days and years can be 365 or 366 days). That's why you need to do the calculation yourself like in the code I posted.
This is a perfect example of why you need to think logic first and code second. You already have all the code you need. All you have to do is check the relative order of the dates and switch them before the calculation if necessary, then negate the numbers at the end if you switched them. All the rest of the code is exactly the same. If you'd thought about the logic first then you wouldn't have had to ask the question at all.
Public Shared Function GetDateSpanText(fromDate As DateTime, toDate As DateTime) As String
Dim swapped = False
If fromDate > toDate Then
Dim temp = fromDate
fromDate = toDate
toDate = temp
swapped = True
End If
Dim years As Integer = 0, months As Integer = 0, days As Integer = 0
Do Until toDate.AddYears(-1) < fromDate
years += 1
toDate = toDate.AddYears(-1)
Loop
Do Until toDate.AddMonths(-1) < fromDate
months += 1
toDate = toDate.AddMonths(-1)
Loop
Do Until toDate.AddDays(-1) < fromDate
days += 1
toDate = toDate.AddDays(-1)
Loop
If swapped Then
years = -years
months = -months
days = -days
End If
Return String.Format("{0} Year(s) {1} Month(s) {2} Day(s)", years, months, days)
End Function

Day360 in vb.net

I want to use the Days360 function in VB.Net. I need to know the difference in days between two dates assuming 360 days in a year (not 365 days the DateDiff function uses).
For example DateDiff(DateInterval.Day,"16/10/2015", "04/02/2016") = 111 days, but Days360 should return 109 days.
Days360 function in Excel calculates the days between two dates using a fictional calendar that has 30 days in each month. This method is used for some financial purposes.
You can write a function to do the same calculation.
[Edit]
Excel supports two versions of the calculation: one common in the US (this is the default) and the other common in Europe (see the documentation of the DAYS360 function for details).
The code I originally posted implemented the European version. I have updated it to support both versions. Thanks to Nikhil Vartak for pointing this out.
Function Days360(startDate As DateTime, endDate As DateTime, euMethod As Boolean) As Integer
Dim months As Integer = (endDate.Year - startDate.Year) * 12 + endDate.Month - startDate.Month
If euMethod Then
'Use European method (start or end dates after the 30th of the month are changed to 30th)
Return months * 30 + Math.Min(30, endDate.Day) - Math.Min(30, startDate.Day)
Else 'Use US method
'If the start date is the last day of the month, change it to the 30th
Dim startDay As Integer = startDate.Day
startDay = If(startDate.Day >= DateTime.DaysInMonth(startDate.Year, startDate.Month), 30, startDate.Day)
'If end date is last of the month, change it to the 30th
Dim endDay As Integer = endDate.Day
endDay = If(endDate.Day >= DateTime.DaysInMonth(endDate.Year, endDate.Month), 30, endDate.Day)
'If end date is last of the month and start date is before 30th, change end date to 1st of the next month
If endDate.Day >= DateTime.DaysInMonth(endDate.Year, endDate.Month) And startDay < 30 Then
endDay = 1
months += 1
End If
Return months * 30 + endDay - startday
End If
End Function

VBA Set a specific date to be the first week of the year

I want to set a specific date (October 06 , 2014) to be the 1st Week of the year. So when I use the =weeknum() formulaR1C1 it will return the week number.
I'm currently working on a worksheet that gets updated daily so the week number will be updated every week only. In column ("D") indicates the week number. and column ("B") indicates the daily date.
If i use the =weeknum() formula on it returns the value of 41, but it needs to be week number 1.
How about creating your personalized function?
It just consists of counting how many days there are between the date you insert (myDate) and the date which is considered to be the first day of the year (first_day), dividing this number by 7, taking its integer and adding up 1. It will always give you the right one.
Public Function special_weeknum(ByVal myDate As Date) As Integer
Dim first_day As Date: first_day = #10/6/2014#
Dim myWeek As Integer: myWeek = Int((myDate - first_day) / 7) + 1
special_weeknum = myWeek
End Function
Please note that this approach would allow you also to pass the first day as a user input:
Public Function special_weeknum(ByVal myDate As Date, ByVal first_day As Date)
Dim myWeek As Integer: myWeek = Int((myDate - first_day) / 7) + 1
special_weeknum = myWeek
End Function
so that you will always be able to decide which is the day you must consider as first day of the year.

VB.NET Make a Date out of just Day

My user will typically enter some trip info including a day and month but typically they just enter the day. For example they would enter "TRIP1500/31" where the 31 is implied that its in JULY. The trip date can be at most 7 days in the past or 7 days in the future. So now what Im trying to do is guess what month that day is meant to be. So far I have:
Dim diff As Integer = CInt(tripDay) - Date.Now.Day
Select Case diff
Case 0
'same day so its probably current month
End Select
What I'm having trouble with is the other cases where the current day and the trip day overlap month-to-month. If the current day and trip day are in current month then the most difference they can be is +/-7 days but what about the other cases? Any help appreciated.
Function GetTripDate(day As Integer) As Date
Dim today As Date = Date.Today
For i As Integer = -7 To 7
Dim dt As Date = today.AddDays(i)
If dt.Day = day Then Return dt
Next
Throw New ArgumentOutOfRangeException("Invalid trip day.")
End Function
This gives you the date(incl. month) of the nearest date with the given day:
Dim maxDiffDays = 7
Dim tripDay = 31
Dim today = Date.Today
Dim tripDate = New Date(today.Year, today.Month, tripDay)
Dim tripDates = {tripDate.AddMonths(-1), tripDate, tripDate.AddMonths(1)}
Array.Sort(Of Date)(tripDates, Function(d1, d2) ((today - d1).Duration).CompareTo((today - d2).Duration))
Dim nearestDate = tripDates.First()
If ((today - nearestDate).Days <= maxDiffDays) Then
Console.WriteLine("Nearest month for trip date is: " & nearestDate.Month)
End If
It creates a Date from a given day, then it creates the two surrounding dates one month after and previous this date. This array will be sorted from the positive timespan from today(TimeSpan.Duration). So the firs't date in the array is the nearest date with the correct month.

Get the week number of the year counting from a given date in VB

In vb we can get the week number counting from January. ex Jan 1st is Week 1 and Feb 1st is Week 5 etc by .DatePart(DateInterval.WeekOfYear, Now)
I need to count the week number from a given date. ex: if set the base to July 1st then July 1st is the week 1 and based on that what would be the week number for Oct 3rd? How can I do this in VB?
You can use Calendar.GetWeekOfYear.
Here's an example
Dim dateNow = DateTime.Now
Dim dfi = DateTimeFormatInfo.CurrentInfo
Dim calendar = dfi.Calendar
' using Thursday because I can.
Dim weekOfyear = calendar.GetWeekOfYear(
dateNow, _
dfi.CalendarWeekRule, _
DayOfWeek.Thursday)
Something like this should do the trick:
Private Function GetWeekNumber(ByVal startMonth As Integer, ByVal startDay As Integer, ByVal endDate As Date) As Integer
Dim span As TimeSpan = endDate - New Date(endDate.Year, startMonth, startDay)
Return (CInt(span.TotalDays) \ 7) + 1
End Function