如何产生日期

时间:2019-06-28 08:15:57

标签: asp.net vb.net

我有一个表单,然后单击按钮,我会自动生成一个准确的日期,即未来一年。我想知道如何确保这个日期不在公众假期或周末。有什么帮助吗?

我想将日期的值存储在变量中,以便将其放在command.Parameters.AddWithValue("@DueDate",___________)

1 个答案:

答案 0 :(得分:0)

您可以为此创建自己的逻辑。这很简单。创建一种检查日期是工作日还是假日的方法。但是您必须对假期进行硬编码,因为假期因国家/地区/大陆/文化等而异。

public bool IsWeekday(DateTime date)
{
    int dayOfWeek = (int)date.DayOfWeek;

    //week starts on sunday
    if (dayOfWeek == 0 || dayOfWeek == 6)
    {
        return false;
    }
    else
    {
        return true;
    }
}


public bool IsHoliday(DateTime date)
{
    int currentYear = DateTime.Now.Year;

    //define your holidays here, they differ between cultures and continents etc
    List<DateTime> holidays = new List<DateTime>()
    {
        new DateTime(currentYear, 1, 1), //new years day
        new DateTime(currentYear, 1, 9), //for testing
        new DateTime(currentYear, 4, 27), //kings day
        new DateTime(currentYear, 6, 21), //longest day of the year
        new DateTime(currentYear, 12, 25), //christmas
        new DateTime(currentYear, 12, 26) //christmas
    };

    //check the date against the list of holidays
    if (holidays.Any(x => x == date.Date))
    {
        return true;
    }
    else
    {
        return false;
    }
}

现在您可以检查它是否有效。

//get a monday
DateTime monday = new DateTime(2019, 1, 7);

//loop all days of the week
for (int i = 0; i < 7; i++)
{
    DateTime nextDay = monday.AddDays(i);
    Label1.Text += string.Format("{0} - {1} - {2}<br>", nextDay.ToLongDateString(), IsWeekday(nextDay), IsHoliday(nextDay));
}

上述循环的结果

maandag 7 januari 2019 - True - False
dinsdag 8 januari 2019 - True - False
woensdag 9 januari 2019 - True - True
donderdag 10 januari 2019 - True - False
vrijdag 11 januari 2019 - True - False
zaterdag 12 januari 2019 - False - False
zondag 13 januari 2019 - False - False