Search code examples
vb.netdate

Trying to list all the mondays and their dates in a year


I'm trying to list all the mondays and their dates in, let's say, 2014. I don't know what's wrong with my code below (probably the loop). When I execute these, the program crashes.

    Dim d1 As DateTime = #1/1/2014#
    Dim d2 As DateTime = d1.AddDays(-(d1.DayOfWeek - DayOfWeek.Monday))

    Do
        ListBox1.Items.Add(d2.ToString("MMM - dd - yyyy   ddd"))
        d2.AddDays(7)
    Loop While (d2.Year < 2015)

Solution

  • A DateTime instance is immutable, meaning that it cannot be changed. The d2.AddDays(7) expression creates a new instance with a different value, which you can assign back to d2:

    d2 = d2.AddDays(7)
    

    So why does your program crash? Since the date never changes, it will never hit 2015, and your program will try to add infinitely many items to the listbox. Obviously you will run out of memory before that happens, which makes the program crash.