【问题标题】:How to Generate Date如何生成日期
【发布时间】:2019-06-28 08:15:57
【问题描述】:

我有一个表格,点击一个按钮,我会自动生成一个正好在未来一年的日期。我想知道如何确保这个日期不是公共假期或周末。有什么帮助吗?

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

【问题讨论】:

  • 周末部分很简单,因为您的DateTime 值具有DayOfWeek 属性。至于公共假期,没有任何内置功能可以做到这一点,因此您只需要将日期与相关公共假期日期列表进行比较。
  • 所以你是说如果我使用 DayOfWeek 那么它会自动忽略周末而只考虑周一到周五的日子? @jmcilhinney
  • 不,您必须选择忽略的日期。 DayOfWeek 只会让您知道日期是星期几。
  • 当有人向您推荐某个类型或成员时,不要只是猜测它的作用或询问他们的作用。去看看它为你自己做了什么。然后应用一些逻辑来说明如何在您的场景中使用它。逻辑在编程中的工作方式与在其他任何地方的工作方式相同。如果有人告诉您他们计划在某个特定日期去某个地方,而您不希望他们在周末去,那么只需找出该日期在一周中的哪一天就可以自动执行任何操作吗?那为什么要在这里呢?

标签: asp.net vb.net


【解决方案1】:

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

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

【讨论】:

  • 这是一个 vb.net 问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 2016-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多