Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last/next week Wednesday date in C#

Tags:

How would I get last week Wednesday and next week Wednesday's date in C#:

public Form1() {    InitializeComponent();    CurrentDate.Text = "Today's Date: " + DateTime.Now.ToString("dd/MM/yyyy");    CurrentRent.Text = "Current Rent Date: "; // last wednesday    NextRent.Text = "Next Rent Date: "; // next wednesday } 
like image 640
methuselah Avatar asked Dec 05 '13 18:12

methuselah


People also ask

How to get last week start Date and end Date in c#?

DateTime pastDate = DateTime. Now. AddDays(-(days + 7));

How do I get the last day of the current month in C#?

You can use the following C# code in the assign activity to get the first and last day of the current month: DateTime now = DateTime. Now; var startDate = new DateTime(now. Year, now.

How do I get the current week number in C#?

You can retrieve the current week number in Schedule control by using the GetWeekOfYear method. In this method, define the CalendarWeekRule class and DayOfWeek class. The CalendarWeekRule class is used to get the first week of the year and the DayOfWeek class is used to get the first day of the week.

How to get day name from Date in c# net?

Use the DateTime. DayOfWeek or DateTimeOffset. DayOfWeek property to retrieve a DayOfWeek value that indicates the day of the week. If necessary, cast (in C#) or convert (in Visual Basic) the DayOfWeek value to an integer.


2 Answers

To find the next Wednesday just keep adding days until you find one. To find the previous Wednesday just keep subtracting days until you get to one.

DateTime nextWednesday = DateTime.Now.AddDays(1); while (nextWednesday.DayOfWeek != DayOfWeek.Wednesday)     nextWednesday = nextWednesday.AddDays(1); DateTime lastWednesday = DateTime.Now.AddDays(-1); while (lastWednesday.DayOfWeek != DayOfWeek.Wednesday)     lastWednesday = lastWednesday.AddDays(-1); 
like image 162
Servy Avatar answered Oct 05 '22 22:10

Servy


Use the AddDays routine:

        // increment by the number of offset days to get the correct date         DayOfWeek desiredDay = DayOfWeek.Wednesday;         int offsetAmount = (int) desiredDay - (int) DateTime.Now.DayOfWeek;         DateTime lastWeekWednesday = DateTime.Now.AddDays(-7 + offsetAmount);         DateTime nextWeekWednesday = DateTime.Now.AddDays(7 + offsetAmount); 

That should do it!

NOTE: If it is a Monday, "Last Wednesday" is going to give you the very last Wednesday that occurred, but "Next Wednesday" is going to give you the Wednesday 9 days from now! If you wanted to get the Wednesday in two days instead you would need to use the "%" operator. That means the second "nextweek" statement would read "(7 + offsetAmount) % 7".

like image 34
drew_w Avatar answered Oct 05 '22 22:10

drew_w