Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

datetime - 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. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...