下面是我的场景:
startDate = 1/7/2012和endDate = 9/7/20124/7/2012和5/7/2012预期结果(DD/MM/YYYY):
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日之外的每一个日期,这些日期已经包含在数据库中。
发布于 2012-07-12 16:54:06
首先,创建要排除(数据库中的日期)的可枚举日期或日期列表。然后,您将希望执行您的循环以获取您指定范围内的所有日期。在该循环中,您将希望将可枚举的所有日期添加到标签中。
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-12 16:37:23
给定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"));
}https://stackoverflow.com/questions/11456391
复制相似问题