Not sure how to go about this. I can find todays date.
string now = System.DateTime.Now.DayOfWeek.ToString();
Console.WriteLine("Today is: " now);
then I have a string that could be any day of the week but no date for it. So lets say all I have is:
string day = "Thursday";
How do I subtract that day (example being Thursday) from now (Monday or todays date 8/15/2022)? What I'm after is the actual date. In this case it would be 8/11/2022 Even getting the number of days from any given day till now would be helpful.
CodePudding user response:
You can maintain an offset map of System.DayOfWeek
that allows you to offset DateTime.Now
based on the current DayOfWeek
.
var now = DateTime.Now;
var dayOfWeek = now.DayOfWeek;
var offset = dayOfWeek switch
{
DayOfWeek.Monday => -6,
DayOfWeek.Sunday => -5,
DayOfWeek.Saturday => -4,
DayOfWeek.Friday => -3,
DayOfWeek.Thursday => -2,
DayOfWeek.Wednesday => -1,
DayOfWeek.Tuesday => -7, // or 0, depending on your needs;
_ => 0
};
var lastTuesday = now.AddDays(offset);
Console.WriteLine(lastTuesday.Date); // Outputs 8/9/2022 12:00:00 AM
CodePudding user response:
You can simply use enum calculations:
int DaysSince(DayOfWeek dow)
{
var today = System.DateTime.Now.DayOfWeek;
return (7 today - dow) % 7;
}
var daysSince = DaysSince(DateOfWeek.Tuesday);
CodePudding user response:
Note that I have based this answer on the actual question, that says you want a date, rather than the title, which says you want a count of days. If you follow the method below, you can increment a variable in the loop to get a count of days.
Here's one option:
private static DateTime GetDateOfLastDayOfWeek(string dayName)
{
if (!Enum.TryParse(dayName, false, out DayOfWeek dayOfWeek))
{
throw new ArgumentException("Not a valid day of week", nameof(dayName));
}
var date = DateTime.Today;
do
{
date = date.AddDays(-1);
} while (date.DayOfWeek != dayOfWeek);
return date;
}
Note that, if today is the specified day, it will go back to the previous instance. If you wanted to match today's date, you could use a while
loop instead of a do
:
while (date.DayOfWeek != dayOfWeek)
{
date = date.AddDays(-1);
}