-3

How can I get 3 days back of current date and should not fall on weekends (Sat/Sun)

Let's say if date i select date as 03/28/2017. It should display date as 03/23/2017. It should not take sat/sun.

dto.ProcessEndDate.AddDays(-3);
user1030181
  • 1,995
  • 5
  • 26
  • 56
  • Shouldn't be displayed 03/24/2017 (Friday), 25th is Saturday? – Darjan Bogdan Mar 30 '17 at 18:39
  • Yea you are right – user1030181 Mar 30 '17 at 18:42
  • 2
    The question is unclear. Suppose you said go back seven days from 3/28/2017. Should that be 3/21/2017, because 3/21/2017 is not a weekend? Or should it be 3/17/2017 because that is 7 business days before 3/21/2017? What if you say "go back zero days", but today is a saturday; does that produce Saturday, or the previous Friday? **Write a clear specification that describes all the possible inputs and desired outputs**, and you will find it is surprisingly easy to write a program. – Eric Lippert Mar 30 '17 at 18:45

1 Answers1

5

This code assumes that if new date falls on a weekend, it will instead return the Friday before.

public static DateTime GetDateExcludeWeekends(DateTime date, int index)
{
    var newDate = date.AddDays(-index);

    if(newDate.DayOfWeek == DayOfWeek.Sunday)
    {
        return newDate.AddDays(-2);
    }

    if(newDate.DayOfWeek == DayOfWeek.Saturday)
    {
        return newDate.AddDays(-1);
    }

    return DateTime.Now;
}

You can tweak the logic, but the main thing is to look at the DayOfWeek enum property of the DateTime class.

maccettura
  • 10,514
  • 3
  • 28
  • 35