简体   繁体   中英

Get the date of the start week of a given date c#

I am trying to get the start of the week from a given date. For example if i passed in a DateTime of 16/08/2018 i would expect a return of 13/08/2018. Everything i have found is to find the start of the current week.

I would do something like this:

Parse the date from string to DateTime object (if required)

Add days current day of the week * -1 (turn it negative) + 1

string s = "2018-08-23 13:26";

DateTime dt = DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

DateTime startOfWeek = dt.AddDays(((int)(dt.DayOfWeek) * -1) + 1);
Console.WriteLine(startOfWeek);

Here's a Fiddle


Edit: If you are bothered about the sunday going to the next Monday, then change the Sunday to remove 7 days from the current date like so;

string s = "2018-08-17 13:26";

DateTime dt = DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

bool isSunday = dt.DayOfWeek == 0;
var dayOfweek = isSunday == false ? (int)dt.DayOfWeek : 7;

DateTime startOfWeek = dt.AddDays(((int)(dayOfweek) * -1) + 1);
Console.WriteLine(startOfWeek);

Get Monday and Sunday of the week with date variable. Can easy try with date variable.

DateTime date = new DateTime(2019, 12, 1);
int day = (int) date.DayOfWeek;
DateTime Monday = date.AddDays((-1) * (day == 0 ? 6 : day - 1));
DateTime Sunday = date.AddDays((1) * (day== 0 ? day : 7 - day)); ```

Super Simple! You can use the DayOfWeek to get how far back you have to go. More info Is avaliable here

Sundays are 0, Mondays are 1.

DateTime date = DateTime.Now; //gets current time
int day = date.DayOfWeek; //gets current day
DateTime Sunday = date.AddDays( (-1) * day ); //go back all the days to get to Sunday
DateTime Monday = date.AddDays( (-1) * (day - 1) ); //go back all the days - 1 to get to Monday

As pointed out by a comment this doesn't work if the current day is on a sunday... So the Monday fix is:

DateTime Monday = date.AddDays( (-1) * (day == 0 ? 7 : day - 1) ); //go back all the days - 1 to get to Monday

Here's a version gives you the monday of the week (assumes that weeks start on monday and end on sunday)

DateTime dt = DateTime.Now;
DateTime startOfWeek = dt.AddDays((((int)(dt.DayOfWeek) + 6) % 7) * -1);    
Console.WriteLine(startOfWeek);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM