VB.NET - Given a date, how can I get the date of last four fridays? - vb.net

Given today's date want to get the date of the each Friday for the last four weeks.

Here is an easy LINQ approach:
Dim today = Date.Today
Dim lastFridays = From d In Enumerable.Range(0, Int32.MaxValue)
Let dt = today.AddDays(-d)
Where dt.DayOfWeek = DayOfWeek.Friday
Select dt
Dim lastFourFridays As Date() = lastFridays.Take(4).ToArray()
Since it's not the most efficient approach, here is a query that is still readable and maintainable but only searches the first friday and then takes only every 7th day:
Dim lastFriday = lastFridays.First() ' reuse of above query '
Dim fridays = From d In Enumerable.Range(0, Int32.MaxValue)
Let dt = lastFriday.AddDays(-d * 7)
Select dt
Dim lastFourFridays As Date() = fridays.Take(4).ToArray()

You may consume this one, which returns a list of such dates and excludes the one if the specifiedDate date is Friday:
Public Shared Function GetLastFourFridays(specifiedDate As DateTime) As List(Of DateTime)
Dim dtm As New List(Of DateTime)()
Dim dt As DateTime = specifiedDate
For i As Integer = 0 To 6
dt = dt.AddDays(-1)
If dt.DayOfWeek = DayOfWeek.Friday Then
dtm.Add(dt)
Exit For
End If
Next
dtm.Add(dt.AddDays(-7))
dtm.Add(dt.AddDays(-14))
dtm.Add(dt.AddDays(-21))
Return dtm
End Function
and the way you use it is:
Dim dtm As List(Of DateTime) = GetLastFourFridays(DateTime.Now)
For Each d As var In dtm
Console.WriteLine(String.Format("Date: {0}, Day: {1}", d.ToString(), [Enum].Parse(GetType(DayOfWeek), d.DayOfWeek.ToString())))
Next

Here is my way:
Function Last4Friday(ByVal StartDate As Date) As array
Dim L4F()
Dim mDate as date = StartDate
For value As Integer = 1 To 7
mDate = mDate.AddDays(-1)
If mDate.DayOfWeek = DayOfWeek.Friday Then
L4F = {mDate, mDate.AddDays(-7), mDate.AddDays(-14), mDate.AddDays(-21)}
exit for
End If
Next
Return L4F
End Function
Edit: If you need to check the inserted date and you want it returned in the array you may simply use:
Dim mDate as date = StartDate.AddDays(1)
instead of
Dim mDate as date = StartDate

Try this. It doesn't use a loop to find the starting Friday.
Dim someDate As DateTime = DateTime.Now
If someDate.DayOfWeek <> DayOfWeek.Friday Then
'do the math to get a Friday
someDate = someDate.AddDays(DayOfWeek.Friday - someDate.AddDays(1).DayOfWeek - 6)
End If
Dim last4Fridays As New List(Of DateTime) From {someDate, someDate.AddDays(-7), someDate.AddDays(-14), someDate.AddDays(-21)}
All of the other suggestions have used a loop to find the starting Friday. If this code is used infrequently then how the starting Friday is determined might not matter.
edit: as function
Function FindLastFourFridays(someDate As DateTime) As List(Of DateTime)
'Find first Friday to include
If someDate.DayOfWeek <> DayOfWeek.Friday Then
someDate = someDate.AddDays(DayOfWeek.Friday - someDate.AddDays(1).DayOfWeek - 6)
' uncomment these two lines if you do not want initial someDate.DayOfWeek = DayOfWeek.Friday to be included
'Else
' someDate = someDate.AddDays(-7)
End If
'build the return (four fridays)
Dim last4Fridays As New List(Of DateTime) From {someDate, someDate.AddDays(-7), someDate.AddDays(-14), someDate.AddDays(-21)}
Return last4Fridays
End Function

This function does not need to be passed a date it picks up today's date and gets the last four Friday's from today. It can be changed around to get any day of the week.
Dim todaysDate As Date = Date.Today
Dim oldDay As Integer
Dim thisWeek As Date
Dim firstWeek As Date
Dim secondWeek As Date
Dim thirdWeek As Date
Dim fourthWeek As Date
'finds the Friday of the end of the current week No mattter what day you are working
Dim daycount As Integer
'use this to check specific dates "Dim datetime As New DateTime(2015, 4, 13)"
oldDay = Weekday(todaysDate)
thisWeek = todaysDate
If oldDay < 6 Then
daycount = 6 - oldDay
thisWeek = thisWeek.AddDays(+daycount)
ElseIf oldDay > 6 Then
daycount = oldDay - 6
thisWeek = thisWeek.AddDays(-daycount)
End If
Dim currentDate As Date = Now
Do While Not currentDate.DayOfWeek = DayOfWeek.Friday
currentDate = currentDate.AddDays(-1)
Loop
fourthWeek = currentDate.AddDays(-21)
thirdWeek = currentDate.AddDays(-14)
secondWeek = currentDate.AddDays(-7)
firstWeek = currentDate

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

How do I get the start date and end date of the current week?

I have a function that returns the current week of the year where we are now, thanks to one of the answers in this forum. Now I need to get the initial date of that week and the final date of that week.
How can I accomplish this?
Protected Friend Function obtenerNumeroSemanas(ByVal dt As DateTime)
Dim cal As Calendar = CultureInfo.InvariantCulture.Calendar
Dim d As DayOfWeek = cal.GetDayOfWeek(dt)
If (d >= DayOfWeek.Monday) AndAlso (d <= DayOfWeek.Wednesday) Then
dt = dt.AddDays(3)
End If
Return cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)
End Function
Dim dayOfWeek = Cint(DateTime.Today.DayOfWeek)
Dim startOfWeek = DateTime.Today.AddDays(-1 * dayOfWeek)
Dim endOfWeek = DateTime.Today.AddDays(7 - dayOfWeek).AddSeconds(-1)
Console.WriteLine(startOfWeek)
Console.WriteLine(endOfWeek)
Using today's date (2016-06-19) results in
2016-06-19 12:00:00 AM
2016-06-25 11:59:59 PM
Dim dayOfWeek = CInt(DateTime.Today.DayOfWeek)
Dim startOfWeek = DateTime.Today.AddDays(+1 * dayOfWeek).ToShortDateString
Dim endOfWeek = DateTime.Today.AddDays(4 + dayOfWeek).AddSeconds(+1).ToShortDateString
MessageBox.Show(startOfWeek)
MessageBox.Show(endOfWeek)
that to get the next monday date and the next friday
Dim result$ = DateTime.Today.AddMonths(-1).ToString("dd-MMM-yyyy")

How to count someday to someday without holiday and Saturday , Sunday (VB) by use Date time picker

enter image description hereHow to count someday to someday without holiday and Saturday , Sunday (VB) by use Date time picker
for leave people system
help me please!
from the picture
left is date start and right is end date
then if I select date both. then count day on the textbox... without Sunday Saturday and Holiday that on Access database...
Count days from start to finish that are not Saturday or Sunday:
Dim startDate As Date = New DateTime(2016, 1, 1)
Dim endDate As Date = DateTime.Now
Dim currentDate = startDate
Dim daysWithoutSatOrSun As Integer = 0
Do
If currentDate.DayOfWeek <> DayOfWeek.Saturday AndAlso currentDate.DayOfWeek <> DayOfWeek.Sunday Then
daysWithoutSatOrSun += 1
End If
currentDate = currentDate.AddDays(1)
Loop Until currentDate > endDate
MessageBox.Show("Days " & daysWithoutSatOrSun)
One readable option is to use LINQ:
Dim days As Int32 = (d2 - d1).Days
Dim weekend = {DayOfWeek.Saturday, DayOfWeek.Sunday }
Dim nonWeekendDays = From d in Enumerable.Range(0, days + 1)
Select day = d1.Date.AddDays(d)
Where Not weekend.Contains(day.DayOfWeek)
Dim countOfDays As Int32 = nonWeekendDays.Count()
If you have List(Of Date) which contains the holidays you can add:
Where Not weekend.Contains(day.DayOfWeek) AndAlso Not holidays.Contains(day)

Fun Logic to minus date with date and get the diffdate vb.net

Ok I cannot think of a algorithm to do this using vb.net.
so here is the 3 variable
Dim DateFrom as date = '01/09/2015'
Dim DateNow as date = Date.Now
Dim Holiday() as date '' <-- List of holiday dates
So what I want to do is I want to get the "Day" diffdate From DateFrom and DateNow and excluding the minus the date in the Holiday() array and also saturday Sunday.
so let say my DateFrom is '01/09/2015' which is Tuesday and my
DateNow is '09/09/2015' which is also tuesday and inside the Holiday() array there's '4/09/2015' Friday. the output of diffdate is suppose to be 5 Day since since (DateNow ---Difference Day minus Holiday()array and also minus saturday and sunday -- DateFrom)
I scratches my head about 152.5 times and still cannot find the way to do this.
I think you can solve this problem using something like this:
Dim intTotalDays As Integer = 0
Dim dtStartDate As New DateTime(2015, 10, 1)
Dim dtEndDate As New DateTime(2015, 10, 31)
Dim Holidays As DateTime() = {
New DateTime(2015, 10, 15),
New DateTime(2015, 10, 17)
}
For i As Integer = 0 To DateDiff(DateInterval.Day, dtStartDate, dtEndDate)
Dim dtDay As DateTime = DateAdd(DateInterval.Day, i, dtStartDate)
If Not dtDay.DayOfWeek = DayOfWeek.Saturday And Not dtDay.DayOfWeek = DayOfWeek.Sunday And Not Holidays.Contains(dtDay) Then
intTotalDays += 1
End If
Next i
MsgBox(intTotalDays)
So you want to determine the number of working-days between two dates?
You can use following LINQ query:
Dim DateFrom As Date = #9/1/2015#
Dim Holiday() As Date = {#9/4/2015#}
Dim Weekend() As DayOfWeek = {DayOfWeek.Saturday, DayOfWeek.Sunday}
Dim days As Int32 = (Date.Today - DateFrom).Days + 1 '+ 1 to include end day '
Dim workingDaysBetween =
From d In Enumerable.Range(0, days)
Let day = DateFrom.AddDays(d)
Where Not Weekend.Contains(day.DayOfWeek) AndAlso Not Holiday.Contains(day)
Dim countDays As Int32 = workingDaysBetween.Count()

How to find weeks between two dates

How to find week's starting date between two dates.
Example:
date1: 4th March 2014.
date2: 18th March 2014.
Then it should return list of weeks begining date as
2014-03-03, 2014-03-10, 2014-03-17
So first you want to get the first day of the week of the start-date? This gives your desired list:
Dim firstDate = New Date(2014, 3, 4)
Dim daysToFirstDay As Int32 = DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek - firstDate.DayOfWeek
firstDate = firstDate.AddDays(daysToFirstDay) ' -1 day in this case
Dim lastDate = New Date(2014, 3, 17)
Dim days As Int32 = (lastDate - firstDate).Days + 1 ' including last
Dim result As List(Of Date) = Enumerable.Range(0, days).
Select(Function(d) firstDate.AddDays(d)).
Where(Function(day) day.DayOfWeek = DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek).
ToList()
It's using LINQ to create a range of Dates between the start-and end-date. Then it uses the current DateTimeFormatInfo's FirstDayOfWeek property to return only week-starting days.
Function GetWeekStartDates(startDate As Date, endDate As Date) As List(Of Date)
Dim result As New List(Of Date)
Dim checkDate = startDate
Dim Is1stWeek As Boolean = True
Do While checkDate <= endDate
If checkDate.DayOfWeek = DayOfWeek.Monday Then
result.Add(checkDate)
If Is1stWeek Then Is1stWeek = False
Else
If Is1stWeek Then
result.Add(checkDate.AddDays(-checkDate.DayOfWeek + 1))
Is1stWeek = False
End If
End If
checkDate = checkDate.AddDays(1)
Loop
Return result
End Function