Week of month, month of year,year - vb.net

I would like to check Week of month, month of year and year but I have a problem with week of month
here is code:
Public Class BMW
Public Shared Function GetWeekNumber() As Integer
Threading.Thread.Sleep(2000)
Dim span As TimeSpan = DateTime.Now - New Date(DateTime.Now.Year, 1, 1)
Return (CInt(span.TotalDays) \ 7) + 1
If span.TotalDays = 1 Then
SendKeys.Send("{1}")
MsgBox(span.TotalDays)
Else
MsgBox("chybi1")
end if
end function

Google is your friend:
Private Function GetWeekNumber() As Integer
Dim span As TimeSpan = DateTime.Now - New Date(DateTime.Now.Year, 1, 1)
Return (CInt(span.TotalDays) \ 7) + 1
End Function
I'm not even sure this is what you are looking for..

Public Shared Function GetWeekNumber(ByVal datum As Date) As Integer
Dim weeknumber = Math.Floor(datum.Day / 7 + +1)
SendKeys.Send(weeknumber)
Return weeknumber
End Function

Related

How many Fridays are there in the month ?. Visual Basic .NET

I want help writing a code to calculate the number of Fridays in a particular month, for example January or February .... etc.
You could use such an iterator method:
Public Iterator Function GetWeekDaysInMonth(year As Int32, month As Int32, dayOfWeek As DayOfWeek) As IEnumerable(Of Date)
Dim day = New Date(year, month, 1)
Dim diff As Int32 = (7 + (day.DayOfWeek - dayOfWeek)) Mod 7
day = day.AddDays(-1 * diff)
If day.Month <> month Then day = day.AddDays(7)
While day.Month = month
Yield day
day = day.AddDays(7)
End While
End Function
Usage:
Dim countFridaysYanuary = GetWeekDaysInMonth(2022, 1, DayOfWeek.Friday).Count()
Dim countFridaysFebruary = GetWeekDaysInMonth(2022, 2, DayOfWeek.Friday).Count()
If you want them all in a list, use:
Dim fridaysInYanuary = GetWeekDaysInMonth(2022, 1, DayOfWeek.Friday).ToList()
If you just want the first:
Dim firstFridayInJanuary = GetWeekDaysInMonth(2022, 1, DayOfWeek.Friday).First()
If you want to output all fridays of the year 2022 per month, you can use:
For i As Int32 = 1 To 12
Dim fridays = GetWeekDaysInMonth(2022, i, DayOfWeek.Friday)
Console.WriteLine(String.Join(", ", fridays.Select(Function(d) d.ToShortDateString())))
Next
Demo: https://dotnetfiddle.net/2ptUlX

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 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

Get the number of months between two DateTimes

mnth = DateDiff(DateInterval.Month, 8/30/2012, 10/1/2012)
gives mnth = 2. But when we look, there is only 32 days between these dates. I am expecting a result mnth=1 as there is only 32 days between these days.
Pls help..
In my scenario i can consider a 15+ days to be a month but if it is less than 15, it should'nt be considered.
To get the number of complete months you can do different things depending on your interpretation,
Public Function CompleteMonthsBetweenA( _
ByVal start As DateTime, _
ByVal end As DateTime) As Integer
Dim invertor = 1
If (start > end) Then
Dim tmp = end
end = start
start = tmp
invertor = -1
End If
Dim diff = ((end.Year - start.Year) * 12) + end.Month - start.Month
If start.Day > end.Day Then
Return (diff - 1) * invertor
Else
Return diff * invertor
End If
End Function
With this function the number of complete months between 31/05/2011 (dd/mm/yy) and 30/06/2011 is 0 but between 30/06/2011 and 31/07/2011 is 1. Which may or may not be what you expect.
Public Function CompleteMonthsBetweenB( _
ByVal start As DateTime, _
ByVal end As DateTime) As Integer
Dim invertor = 1
If (start > end) Then
Dim tmp = end
end = start
start = tmp
invertor = -1
End If
Dim diff = ((end.Year - start.Year) * 12) + end.Month - start.Month
Dim startDaysInMonth = DateTime.DaysInMonth(start.Year, start.Month)
Dim endDaysInMonth = DateTime.DaysInMonth(end.Year, end.Month)
If (start.Day / startDaysInMonth) > (end.Day / endDaysInMonth) Then
Return (diff - 1) * invertor
Else
Return diff * invertor
End If
End Function
With this function the ratio Day / DaysInMonth is taken so the relative completion of the two months can be assessed.
Public Function CompleteMonthsBetweenC( _
ByVal start As DateTime, _
ByVal enddate As DateTime) As Integer
Dim invertor = 1
If (start > enddate) Then
Dim tmp = enddate
enddate = start
start = tmp
invertor = -1
End If
Dim diff = ((enddate.Year - start.Year) * 12) + enddate.Month - start.Month
Dim remainingDays = _
(DateTime.DaysInMonth(start.Year, start.Month) - start.Day) + enddate.Day
If remainingDays < 15 Then
Return (diff - 1) * invertor
Else
Return diff * invertor
End If
End Function
This function only rounds down if the surplus days are less than the magic number 15, which I think is what you are asking for in your update.
Public Function CompleteMonthsBetweenD( _
ByVal start As DateTime, _
ByVal end As DateTime) As Integer
Return end.Subtract(start).TotalDays \ 30.436875
End Function
This function takes the simpler approach of dividing the total number of days by the average number of days per month in the Gregorian Calendar.
The difference in months is calculated without regard to the day component of the dates.
For example, the difference in months between 8/31/2012 and 9/1/2012 is 1, eventhough it's only one day between the dates.
If you want to consider the day component you have to get the date difference in days instead of months, and calculate how many months you want that to be.
This is the class I use (it's C# but really easy to convert to VB.NET).
It is usefull for years, months, days... it is ideal for displaying ages in #Y-#M-#D format.
public class DateDifference
{
/// <summary>
/// defining Number of days in month; index 0=> january and 11=> December
/// february contain either 28 or 29 days, that's why here value is -1
/// which wil be calculate later.
/// </summary>
private int[] monthDay = new int[12] { 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
/// <summary>
/// contain from date
/// </summary>
private DateTime fromDate;
/// <summary>
/// contain To Date
/// </summary>
private DateTime toDate;
/// <summary>
/// this three variable for output representation..
/// </summary>
private int year;
private int month;
private int day;
public DateDifference(DateTime d1, DateTime d2)
{
int increment;
if (d1 > d2)
{
this.fromDate = d2;
this.toDate = d1;
}
else
{
this.fromDate = d1;
this.toDate = d2;
}
///
/// Day Calculation
///
increment = 0;
if (this.fromDate.Day > this.toDate.Day)
{
increment = this.monthDay[this.fromDate.Month - 1];
}
/// if it is february month
/// if it's to day is less then from day
if (increment == -1)
{
if (DateTime.IsLeapYear(this.fromDate.Year))
{
// leap year february contain 29 days
increment = 29;
}
else
{
increment = 28;
}
}
if (increment != 0)
{
day = (this.toDate.Day + increment) - this.fromDate.Day;
increment = 1;
}
else
{
day = this.toDate.Day - this.fromDate.Day;
}
///
///month calculation
///
if ((this.fromDate.Month + increment) > this.toDate.Month)
{
this.month = (this.toDate.Month + 12) - (this.fromDate.Month + increment);
increment = 1;
}
else
{
this.month = (this.toDate.Month) - (this.fromDate.Month + increment);
increment = 0;
}
///
/// year calculation
///
this.year = this.toDate.Year - (this.fromDate.Year + increment);
}
public override string ToString()
{
//return base.ToString();
return this.year + " Year(s), " + this.month + " month(s), " + this.day + " day(s)";
}
public int Years
{
get
{
return this.year;
}
}
public int Months
{
get
{
return this.month;
}
}
public int Days
{
get
{
return this.day;
}
}
}
USAGE:
DateDifference diff = new DateDifference(date1, date2);
int months = (diff.Years*12) + diff.Months + diff.Days > 15 ? 1 : 0;
If you want the number of complete month, then you'll need to compare date that starts at the begining of the closet month.
Sub Main()
' mnth = DateDiff(DateInterval.Month, 8/30/2012, 10/1/2012)
Console.WriteLine(GetCompleteMonthCount(New DateTime(2012, 8, 30), New DateTime(2012, 10, 1)))
Console.ReadLine()
End Sub
Public Function GetCompleteMonthCount(ByVal d1 As DateTime, ByVal d2 As DateTime) As Integer
If d1.Day <> 1 Then
d1 = d1.AddMonths(1)
d1 = New DateTime(d1.Year, d1.Month, 1)
End If
If d2.Day <> 1 Then
d2 = New DateTime(d2.Year, d2.Month, 1)
End If
Return DateDiff(DateInterval.Month, d1, d2)
End Function
The solutions above are all very good but perhaps a little over-complicated, how about
Function wholeMonthsEd(d1, d2) As Integer
' determine the DateDiff function output
' which gives calendar month difference
initMonths = DateDiff("m", d1, d2)
' do calcs on the Day of the month to deduct/not a calendar month
If Day(d2) < Day(d1) Then
initMonths = initMonths - 1
End If
wholeMonths = initMonths
End Function

Finding the date of monday in a week with VB.NET

I need to find a way to find the date (DD/MM/YYYY) of the Monday for any week we're on.
For example, for this week, monday would be 09/11/2009, and if this were next week it'd be 16/11/2009.
I managed to get somewhere in the forms of code, but all I got was 'cannot convert to Integer' errors. I was using Date.Today and AddDays().
Thanks for any help. :)
If Sunday is the first day of week, you can simply do this:
Dim today As Date = Date.Today
Dim dayDiff As Integer = today.DayOfWeek - DayOfWeek.Monday
Dim monday As Date = today.AddDays(-dayDiff)
If Monday is the first day of week:
Dim today As Date = Date.Today
Dim dayIndex As Integer = today.DayOfWeek
If dayIndex < DayOfWeek.Monday Then
dayIndex += 7 'Monday is first day of week, no day of week should have a smaller index
End If
Dim dayDiff As Integer = dayIndex - DayOfWeek.Monday
Dim monday As Date = today.AddDays(-dayDiff)
DateTime.DayOfWeek is an enum that indicates what day a given date is. As Monday is 1, you can find the Monday of the current week using the following code:
Dim monday As DateTime = Today.AddDays((Today.DayOfWeek - DayOfWeek.Monday) * -1)
=Format(DateAdd("d", (-1 * WeekDay(Date.Today()) + 2), Date.Today()), "dd/MM/yyyy")
A simple method should get you what you want:
private static DateTime GetMondayForWeek(DateTime inputDate)
{
int daysFromMonday = inputDate.DayOfWeek - DayOfWeek.Monday;
return inputDate.AddDays(-daysFromMonday);
}
You could also extend it for any day that you want as well:
private static DateTime GetDayForWeek(DateTime inputDate, DayOfWeek inputDay)
{
int daysAway = inputDate.DayOfWeek - inputDay;
return inputDate.AddDays(-daysAway);
}
To call the first example just use something like:
DateTime mondayDate = GetMondayForWeek(new DateTime(2009, 11, 15));
Console.WriteLine(mondayDate);
Another approach if Monday is the first day, is this:
Dim today As Date = Date.Today
Dim dayDiff As Integer = today.DayOfWeek - DayOfWeek.Monday
Dim monday As Date = today.AddDays(-dayDiff)
dayDiff = DayOfWeek.Saturday - today.DayOfWeek + 1
Dim sunday As Date = today.AddDays(dayDiff)
There is a day of week method that you can use
Dim instance As DateTime
Dim value As DayOfWeek
value = instance.DayOfWeek
see: http://msdn.microsoft.com/en-us/library/system.datetime.dayofweek.aspx
I just did this in a project I'm working on --I promise, it's correct. This is a method that returns the nth monday after the given date. If the given date is a monday, it returns the next monday.
Public Function GetSubsequentMonday(ByVal startDate As DateTime, ByVal subsequentWeeks As Integer) As DateTime
Dim dayOfWeek As Integer = CInt(startDate.DayOfWeek)
Dim daysUntilMonday As Integer = (Math.Sign(dayOfWeek) * (7 - dayOfWeek)) + 1
'number of days until the next Monday
Return startDate.AddDays(CDbl((daysUntilMonday + (7 * (subsequentWeeks - 1)))))
End Function
Following on from my comments to Meta-Knight's answer, here is a short function that makes the correction I mention in the comments:
Public Function GetFirstOfLastWeek() As DateTime
Dim today As DateTime, daysSinceMonday As Integer
today = DateTime.Today
daysSinceMonday = today.DayOfWeek - DayOfWeek.Monday
If daysSinceMonday < 0 Then
daysSinceMonday += 7
End If
Return today.AddDays(-daysSinceMonday)
End Function
And if your week starts from Monday then you can use something like this:
DateTime mondayDate = DateTime.Now.AddDays(((DateTime.Now.DayOfWeek == DayOfWeek.Sunday?7: (int)DateTime.Now.DayOfWeek) - 1)*-1);
DateTime sundayDate = DateTime.Now.AddDays(7 - (DateTime.Now.DayOfWeek == DayOfWeek.Sunday?7: (int)DateTime.Now.DayOfWeek ));
Dim dayOfWeek = CInt(DateTime.Today.DayOfWeek)
Dim startOfWeek = DateTime.Today.AddDays(+1 * dayOfWeek).ToShortDateString
Dim endOfWeek = DateTime.Today.AddDays(6 + dayOfWeek).AddSeconds(+1).ToShortDateString
MessageBox.Show(startOfWeek)
MessageBox.Show(endOfWeek)
Example:
If today is 03/09/2020,
startOfWeek will be 07/09/2020 and
endOfWeek will be 13/09/2020.