如果今天是星期一,我如何获得星期五的约会

时间:2011-12-21 10:01:20

标签: c# asp.net c#-4.0

我有.Net项目由于某种原因我需要有日期。

我做得很好 var date = DateTime.Today.AddDays(-1); 这给了我yesterday's日期。 但如果我在Monday上运行我的应用程序,那么我应该Friday日期

请建议我表达这个。

例如,

。 如果今天为Monday且日期为21/12/2001则应该给我19/12/2001,即Fridays日期 如果今天为Tuesday且日期为21/12/2001,则应正常返回20/12/2001

6 个答案:

答案 0 :(得分:19)

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);
    }
}

答案 1 :(得分:3)

这应该可以解决问题:

var date = DateTime.Now.DayOfWeek == DayOfWeek.Monday ? DateTime.Today.AddDays(-3) : DateTime.Today.AddDays(-1);

答案 2 :(得分:2)

//Check if the date is a sunday, if so deduct three days instead
if(date.DayOfWeek == DayOfWeek.Sunday) date = DateTime.Today.AddDays(-3)

答案 3 :(得分:0)

根据我上面的评论,假设你想要上一个工作日:

    public static DateTime GetPreviousWorkingDay(DateTime fromDate)
    {
        while ((fromDate=(fromDate.Date - TimeSpan.FromDays(1))).DayOfWeek == DayOfWeek.Sunday | fromDate.DayOfWeek == DayOfWeek.Saturday)
        {}

        return fromDate;
    }

答案 4 :(得分:0)

        DateTime today = DateTime.Now;
        DateTime lastWorkingDay;
        if (today.DayOfWeek == DayOfWeek.Monday) 
        {
            lastWorkingDay = today.AddDays(-3);
        }
        else
        {
            lastWorkingDay = today.AddDays(-1);
        }

        Console.WriteLine(lastWorkingDay);

答案 5 :(得分:0)

要扩大Riks答案,如果您还需要处理国家法定假日:

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);
   }
}  

如何填写公众假期清单对你来说真的很不错......