Reputation: 16219
I have .Net project for some reason i need to have date to be taken.
I have done like
var date = DateTime.Today.AddDays(-1);
which is giving me yesterday's
date.
but if I run my application on Monday
then I should get Friday
date
please suggest me expression for this.
for example.
if today is Monday
and date is 21/12/2001
it should give me 19/12/2001
i.e Fridays
date
if today is Tuesday
and date is21/12/2001
it should return me 20/12/2001
as normal
Upvotes: 3
Views: 9763
Reputation: 1647
This should do the trick:
var date = DateTime.Now.DayOfWeek == DayOfWeek.Monday ? DateTime.Today.AddDays(-3) : DateTime.Today.AddDays(-1);
Upvotes: 2
Reputation: 33857
To expand on Riks answer, if you also need to handle national holidays:
private Date[] _publicHolidays = { new Date(2011, 12, 25) };
public Date GetPreviousWorkingDay(Date date)
{
Date previousDay;
switch(date.DayOfWeek)
{
case DayOfWeek.Sunday:
previousDay = date.AddDays(-2);
case DayOfWeek.Monday:
previousDay = date.AddDays(-3);
default:
previousDay = date.AddDays(-1);
}
if (_publicHolidays.Contains(previousDay))
{
return GetPreviousWorkingDay(previousDay);
}
}
How you populate your list of public holidays is really down to you...
Upvotes: 0
Reputation: 498
DateTime today = DateTime.Now;
DateTime lastWorkingDay;
if (today.DayOfWeek == DayOfWeek.Monday)
{
lastWorkingDay = today.AddDays(-3);
}
else
{
lastWorkingDay = today.AddDays(-1);
}
Console.WriteLine(lastWorkingDay);
Upvotes: 0
Reputation: 13335
Assuming you want the previous working day as per my comment above:
public static DateTime GetPreviousWorkingDay(DateTime fromDate)
{
while ((fromDate=(fromDate.Date - TimeSpan.FromDays(1))).DayOfWeek == DayOfWeek.Sunday | fromDate.DayOfWeek == DayOfWeek.Saturday)
{}
return fromDate;
}
Upvotes: 0
Reputation: 29243
public DateTime GetPreviousWorkingDay(DateTime date)
{
switch(date.DayOfWeek)
{
case DayOfWeek.Sunday:
return date.AddDays(-2);
case DayOfWeek.Monday:
return date.AddDays(-3);
default:
return date.AddDays(-1);
}
}
Upvotes: 19
Reputation: 2878
//Check if the date is a sunday, if so deduct three days instead
if(date.DayOfWeek == DayOfWeek.Sunday) date = DateTime.Today.AddDays(-3)
Upvotes: 2