Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

finding the Last Monday Date

Status
Not open for further replies.

litton1

Technical User
Apr 21, 2005
584
GB
What is the best way to find the date of the previous Monday?

At the moment I am using a DateTime type and subtracting 1 out of the constructor until I get to a Monday. Must be better way…? Thx T


Age is a consequence of experience
 
Solved!

Age is a consequence of experience
 
Please post your solution so the rest of the world can benefit.
 
Sorry, what I did was, I used a date time picker just for this, I made it visible = false so it wasn’t actually viewable. Then I wrote this function
Code:
		private void SetDTPToLastMonday()
		{
			string aDay = dtpMonday.Value.DayOfWeek.ToString();

			//create a time span object of one day
			System.TimeSpan ad = new TimeSpan(1,0,0,0);
			if(aDay != "Monday")
			{
				do 
				{
					dtpMonday.Value = dtpMonday.Value.Subtract(ad);
					aDay = dtpMonday.Value.DayOfWeek.ToString();
                }while (aDay != "Monday");
			}
			
		}

Age is a consequence of experience
 
a nice recursive algorithm would do just as well

somtehing like

Code:
 private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = searchlastmonday(1).ToString("dd/MM/yyyy");   

        }

        private DateTime searchlastmonday(int tosubstract)
        {
            if ((System.DateTime.Today.AddDays(-tosubstract)).DayOfWeek != System.DayOfWeek.Monday)
            {
                searchlastmonday(tosubstract -= 1);
            }
            return System.DateTime.Today.AddDays(-tosubstract);
        }

Christiaan Baes
Belgium

I just like this --> [Wiggle] [Wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top