This is my issue, I want to return the Monday of a given week in date format.
Here I have my effort so far.
Code:
Dim Diff
Dim cDate
Dim prday
prday = [table.datefield]
Diff = Cint(0 - (Weekday(prday, 2)))
cDate = DateAdd("d", Diff, prday)
Result = cDate
However, this rather unfortunately returns 24/12/1899. Not exactly what I want.. 2013 would be nice. Any tips for where I went wrong?
Note:
The specific date which is pulled out of the database table is done in a different application. This code is supposed to generate a date which will be shown on a label.
The only issue is how you want to treat Sunday dates.
'Sunday as first day of week
Dim someDate As DateTime = DateTime.Parse("Apr 28, 2013")
'calculate monday
'note: for Sunday this returns next Monday, i.e Apr 28, 2013 returns Apr 29th
Dim monDate As DateTime = someDate.AddDays(DayOfWeek.Monday - someDate.DayOfWeek)
'Monday as first day of week
Dim someDate As DateTime = DateTime.Parse("Apr 28, 2013")
'calculate monday
If someDate.DayOfWeek = DayOfWeek.Sunday Then someDate = someDate.AddDays(-1)
Dim monDate As DateTime = someDate.AddDays(DayOfWeek.Monday - someDate.DayOfWeek)
Define an extension method
Imports System.Runtime.CompilerServices
Module DateExtensions
<Extension()>
Public Function GetMonday(ByVal dt As DateTime) as DateTime
While dt.DayOfWeek <> DayOfWeek.Monday
dt = dt.AddDays(-1)
End While
return dt
End Function
End Module
And call it
prday = prday.GetMonday()
Or we could make it generic
Public Function GetPreviousDayOfWeek(ByVal dt As DateTime, prevDay As DayOfWeek) as DateTime
While dt.DayOfWeek <> prevDay
dt = dt.AddDays(-1)
End While
return dt
End Function
As pointed out by #dbasnett a math is faster than a loop and we could handle the situation when Sunday is the first day of week. So a better approach should be
Public Function GetMonday(ByVal dt As DateTime) as DateTime
Dim diff = Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek - DayOfWeek.Monday
dt = dt.AddDays(diff)
return dt.AddDays(DayOfWeek.Monday - dt.DayOfWeek)
End Function
Related
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")
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
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
iam trying to get the Dates (Monday - Sunday) for the current Week.
This is my current Code:
Dim kw As Integer = DatePart(DateInterval.WeekOfYear, Now, , FirstWeekOfYear.FirstFourDays)
If DatePart(DateInterval.Weekday, Now, Microsoft.VisualBasic.FirstDayOfWeek.Sunday) = 6 Then
kw = kw + 1
End If
Dim CurrDateFirstDay As Date = DateAdd(DateInterval.Day, 1, ReturnDateForWeekNumber(kw))
For i = 1 To 7
strCurrDay = FormatDateTime(CurrDateFirstDay, DateFormat.LongDate)
........
My Problem is that my code starts at 16.01.2013 and the last date is Thuesday 22.01.2013 next week. Why is that? Why does he start Wednesday 16.01.2013 and not Monday 14.01.2013? And why do i get returned dates of the next week? What iam doing wrong?
Edit:
ReturnDateForWeekNumber:
Public Shared Function ReturnDateForWeekNumber(ByVal iWeek As Integer) As DateTime
Return DateAdd(DateInterval.WeekOfYear, iWeek - 1, FirstDayOfYear)
End Function
What am I doing wrong?
You should step through your code in the debugger and observe the result, as I did:
Dim kw As Integer = DatePart(DateInterval.WeekOfYear, Now, , FirstWeekOfYear.FirstFourDays)
This returns the current week, which is week 3.
If DatePart(DateInterval.Weekday, Now, Microsoft.VisualBasic.FirstDayOfWeek.Sunday) = 6 Then
kw = kw + 1
End If
This checks if the weekday is the 6th day of the week (friday). We're not friday so If condition is not entered.
Dim CurrDateFirstDay As Date = DateAdd(DateInterval.Day, 1, ReturnDateForWeekNumber(kw))
This adds one day to the result of ReturnDateForWeekNumber, which returns:
Return DateAdd(DateInterval.WeekOfYear, iWeek - 1, FirstDayOfYear)
This adds 2 (week 3 minus 1) weeks to the first day of the year (Jan 1st), a tuesday. Jan 1st + 2 weeks = January 15th.
Now remember that you add one day to ReturnDateForWeekNumber, that's why CurrDateFirstDay has a value of January 16th.
Edit
I think your code is overly complicated and uses a lot of legacy VB6 functions. I would do it this way:
Dim myDate As Date = DateTime.Today
Dim dayDiff As Integer = myDate.DayOfWeek - DayOfWeek.Monday
Dim currentDay As Date = myDate.AddDays(-dayDiff) 'Monday
For i = 1 to 7
Console.WriteLine(currentDay)
'Do something with current day
currentDay = currentDay.AddDays(1)
Next
You might have to do some adjustments for your case but I believe this approach is simpler and less error prone.
Dim dateStartDateOfWeek As Date = GetWeekStartDate(52, 2014)
Dim dateEndDateOfWeek As Date = DateAdd(DateInterval.Day, 7, dateStartDateOfWeek)
Private Function GetWeekStartDate(ByVal weekNumber As Integer, ByVal year As Integer) As Date
Dim startDate As New DateTime(year, 1, 1)
Dim weekDate As DateTime = DateAdd(DateInterval.WeekOfYear, weekNumber - 1, startDate)
Return DateAdd(DateInterval.Day, (-weekDate.DayOfWeek) + 1, weekDate)
End Function
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.