views:

72

answers:

2

Hi folks,

I wanna have a drop down that lets me select "Week Commencing Monday the 20th" going back 10 Mondays but I'm not sure how to go about doing this.

I've used date.now(), etc. before but not sure how to do this one.

Thanks, Billy

UPDATED CODE

Public Sub GetMondays()
    Dim dtMondays As New DataTable()
    dtMondays.Columns.Add("Date")
    Dim i As Integer = 1
    While (dtMondays.Rows.Count < 11)
        Dim Day As DateTime = Today.AddDays(-i)
        If Day.DayOfWeek = 1 Then
            dtMondays.Rows.Add(Day)
        End If
        i += 1

    End While

    drpDate.DataSource = dtMondays
    drpDate.DataBind()

End Sub
+2  A: 

You could come up with a formula for calculating the dates of the previous Mondays, but why not do something simple:

  • Begin loop.
  • Subtract one day.
  • Check if it is Monday.
    • If so, add to a list.
    • If the list contains 10 elements, exit loop.
  • Go back to start of loop.

I'm sure you can implement that. It's not that fastest way, but it's simple and probably fast enough for most purposes. If you want to optimize it, you can do so, but it's probably not worth your time unless this is being executed many times per second.

Mark Byers
hey thanks that worked though it is a bit slow. Can u check out my code, i've added it to the question. Ta!
iamjonesy
@Jonesy: I'd use DayOfWeek.Monday instead of 1 ( http://msdn.microsoft.com/en-us/library/system.datetime.dayofweek.aspx ) and test against 10 (e.g. <= 10) rather than 11.
Mark Byers
@Mark - thanks!
iamjonesy
+1  A: 

Let's work through it. I'll do this in C# but hopefully some enterprising young polyglot can do the translation for me and score the accepted answer.

DateTime.Today gets you today's date. DateTime.Today.DayOfWeek gets you today's "day of the week" as an enum, where Sunday is 0 and Saturday is 6.

So we can get the latest Monday using:

var lastMonday = DateTime.Today.AddDays(1 - (int)DateTime.Today.DayOfWeek);

edit There's one little glitch here, in that if today is Sunday you'll be getting tomorrow's date, not last Monday's. There's probably some really tricky mathematical way to get around that, but it's just as easy to throw in an extra check:

if (lastMonday > DateTime.Today) lastMonday = lastMonday.AddDays(-7);

Then we just need to get ten of them:

var lastTenMondays = from i in Enumerable.Range(0, 10)
                     select lastMonday.AddDays(i * -7);
Matt Hamilton
To get the latest Monday without the if statement: lastMonday = DateTime.Today.AddDays(-((int)DateTime.Today.DayOfWeek + 6) % 7); use MOD instead of % for VB
B Pete
@B Pete nice! Like I suggested, you should translate my code to VB.NET and post it as your own answer.
Matt Hamilton