0

这是我的场景:

  1. 给定startDate = 1/7/2012endDate = 9/7/2012
  2. 数据库包含:4/7/20125/7/2012
  3. 读取并返回不包含在数据库中的时间间隔的日期

预期结果(日/月/年):

1/7/2012
2/7/2012
3/7/2012
6/7/2012
7/7/2012
8/7/2012
9/7/2012

以下是我正在使用的代码:

DateTime startDate = new DateTime(2012, 7, 1, 0, 0, 0);
DateTime endDate = new DateTime(2012, 7, 9, 0, 0, 0);
int interval = 1;

MySqlConnection connDate = new MySqlConnection(connectionString);
MySqlCommand cmdDate = connDate.CreateCommand();

cmdDate.Parameters.Add("username", MySqlDbType.VarChar);
cmdDate.Parameters["username"].Value = Session["username"].ToString();

cmdDate.CommandText = "SELECT * FROM report WHERE username = @username";

connDate.Open();

MySqlDataReader drDate = cmdDate.ExecuteReader();
this.Label1.Text = "";

for (DateTime dateTime = startDate; dateTime < endDate; dateTime += TimeSpan.FromDays(interval))
{
    //start from here, i don't know exactly what i am doing.
    DateTime reportDate = Convert.ToDateTime(null);
    while (drDate.Read())
    {
        reportDate = Convert.ToDateTime(drDate["reportDate"].ToString());
    }

    if (Convert.ToDateTime(drDate["reportDate"].ToString()).ToShortDateString() != reportDate.ToShortDateString())
    {
        this.Label1.Text += dateTime.ToString() + "</br>";
    }
}
connDate.Close();

问题是,上面的代码显示了 2012 年 7 月 1 日至 9 日的所有日期。相反,我希望它显示除数据库中已包含的 7 月 4 日和 5 日之外的所有日期。

4

2 回答 2

3

给定startDate, endDate, 和每日间隔:

// Assumes IEnumerable<DateTime> dbDates;
var remaining =
    Enumerable.Range(0, Int32.MaxValue)
              .Select(day => startDate.AddDays(day))
              .Where(d => d <= endDate)
              .Except(dbDates);

或者也许是更熟悉的迭代方法:

// Given: HashSet<DateTime> except = new HashSet<DateTime>(dbDates);
for (DateTime date = startDate;
     date <= endDate;
     date = date.AddDays(1))
{
    if (except.Contains(date)) continue;

    // We now have 'date' which is unused in the db
}

为了帮助从数据库中检索,您可以使用GetDateTime重载:

// List<DateTime> is another option if you care about order
var dbDates = new HashSet<DateTime>();
while (drDate.Read())
{
    dbDates.Add(drDate.GetDateTime("reportDate"));
}
于 2012-07-12T16:37:23.223 回答
1

首先,创建要排除的可枚举或日期列表(数据库中的日期)。然后,您将需要执行循环以获取指定范围内的所有日期。在该循环中,您需要将所有未包含在可枚举中的日期添加到标签中。

IList<DateTime> exclusionDates = new List<DateTime>();

while (drDates.read())
{
    exclusionDates.Add(Convert.ToDateTime(drDates["reportDate"].ToString()));
}

for (DateTime dateTime = startDate; dateTime < endDate; dateTime += TimeSpan.FromDays(interval))
{
    if (!exclusionDates.Contains(dateTime))
    {
        this.Label1.Text += dateTime.ToString() + "</br>";
    }
}
于 2012-07-12T16:54:06.807 回答