使用以下代码,我可以在MySql表中插入日期范围,但是我需要根据工作日限制日期。 例如,我想限制所有日期进入星期三。
protected void Submit_click(object sender, EventArgs e)
{
DateTime startdate = Convert.ToDateTime(txtstartdate.Text);
DateTime enddate = Convert.ToDateTime(txtenddate.Text);
for (DateTime date = startdate; date <= enddate; date = date.AddDays(1))
{
try
{
var shtdate = date.ToShortDateString();
string MyConString = "SERVER=localhost;DATABASE=mydb;UID=myid;PASSWORD=abc123;";
MySqlConnection connection = new MySqlConnection(MyConString);
string cmdText = "INSERT INTO approved(agentlogin ,leavetype ,date ,time, reason)VALUES ( @login, @type, @date, 'Full day', @reason)";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.AddWithValue("@login", Label1.Text);
cmd.Parameters.AddWithValue("@type", ddlleavetype.Text);
cmd.Parameters.AddWithValue("@date", shtdate);
cmd.Parameters.AddWithValue("@reason", txtreason.Text);
connection.Open();
int result = cmd.ExecuteNonQuery();
connection.Close();
//lblError.Text = "Data Saved";
}
catch (Exception)
{
Console.Write("not entered");
//lblError.Text = ex.Message;
}
}
}
那我该怎么办呢?感谢您的帮助
答案 0 :(得分:1)
您可以尝试DateTime.DayOfWeek
跳过所有具有DayOfWeek.Wednesday
或DayOfWeek.Thursday
的日期,如下所示:
for (DateTime date = startdate; date <= enddate; date = date.AddDays(1))
{
if (date.DayOfWeek == DayOfWeek.Wednesday || date.DayOfWeek == DayOfWeek.Thursday)
{
// skip to next day
continue;
}
try
{
// write to database
}
catch (Exception)
{
Console.Write("not entered");
//lblError.Text = ex.Message;
}
}
答案 1 :(得分:0)
DateTime具有DayOfWeek属性。 (请检查here)。
您只需在if语句中使用它,就可以了。
答案 2 :(得分:0)
我不是根据星期三和星期四的两个工作日来制定条件,而是根据其他所有5天来编写条件,如下所示。
protected void Submit_click(object sender, EventArgs e)
{
DateTime startdate = Convert.ToDateTime(txtstartdate.Text);
DateTime enddate = Convert.ToDateTime(txtenddate.Text);
for (DateTime date = startdate; date <= enddate; date = date.AddDays(1))
{
if (date.DayOfWeek == DayOfWeek.Monday || date.DayOfWeek == DayOfWeek.Tuesday || date.DayOfWeek == DayOfWeek.Friday || date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
{
var shtdate = date.ToShortDateString();
string MyConString = "SERVER=localhost;DATABASE=mydb;UID=myid;PASSWORD=abc123;";
MySqlConnection connection = new MySqlConnection(MyConString);
string cmdText = "INSERT INTO approved(agentlogin ,leavetype ,date ,time, reason)VALUES ( @login, @type, @date, 'Full day', @reason)";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.AddWithValue("@login", Label1.Text);
cmd.Parameters.AddWithValue("@type", ddlleavetype.Text);
cmd.Parameters.AddWithValue("@date", shtdate);
cmd.Parameters.AddWithValue("@reason", txtreason.Text);
connection.Open();
int result = cmd.ExecuteNonQuery();
}
else{
}
}
}