以下是我的情景:
startDate = 1/7/2012
和endDate = 9/7/2012
4/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日之外的所有日期,这些日期已包含在数据库中。
答案 0 :(得分: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"));
}
答案 1 :(得分: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>";
}
}