C# 中的月历

本文关键字:月历 | 更新日期: 2023-09-27 18:31:41

我有数据库,我使用 SQL 查询将数据从中获取到我的 C# 应用程序。

我的应用程序中有选项,可以从月历中选择当天的数据:

"between '" + monthCalendar1.SelectionStart.Month.ToString() + "' and '" + monthCalendar1.SelectionStart.AddDays(1).ToString()+

因此,当我从日历窗体中选择 2012-03-06 时,我的 SQL 查询会得到这样的内容:

between '2012-03-06' and '2012-03-12'

它正在起作用。

现在我想获取整个月的数据 - 如何修改 sql 查询的一部分,所以当我选择四月的一天时,我得到这个:

between '2012-04-01' and '2012-04-30'

编辑:我取得了一些进展 - 我有每月的第一天,但如何获得最后一天?

monthCalendar1.SelectionStart.Year.ToString()+"-"+monthCalendar1.SelectionStart.Month.ToString().PadLeft(2,'0')+"-"+"01"

C# 中的月历

永远不要把你的SQL语句作为字符串放在一起!还记得鲍比表...

除此之外:

DateTime someDay = ...;
DateTime firstOfMonth = new DateTime(someDay.Year, someDay.Month, 1);
DateTime lastOfMonth = firstOfMonth.AddMonths(1).AddDays(-1);
string sqlString = "SELECT ... FROM ... WHERE ... AND ... BETWEEN @d1 AND @d2";
using (SqlCommand cmd = new SqlCommand(sqlString, connection))
{
    cmd.Parameters.AddWithValue("@d1", firstOfMonth);
    cmd.Parameters.AddWithValue("@d2", lastOfMonth);
    ...
}

编辑
想一想:您实际上会注意到您想要的内容不会返回任何介于 lastOfMonth 00:00:01lastOfMonth 23:59:59 之间的条目。实际上,您应该从所选月份的第一天到下个月的第一天进行查询以获取所需的信息(减去一毫秒而不是一天无济于事,因为SQL Server无法完全存储毫秒)。

DateTime startDate = new DateTime(dt.Year, dt.Month, 1);
DateTime enddate = new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));

between '" + startDate.ToString("yyyy-MM-dd") + "' and '" + enddate.ToString("yyyy-MM-dd")+

使用它来获取所选月份的最后一天

DateTime.DaysInMonth(dt.Year, dt.Month);

http://social.msdn.microsoft.com/Forums/en/Vsexpressvcs/thread/218260ec-b610-4fa6-9d1b-f56f3438b721

    DateTime startDate = DateTime.Parse("03.04.2012");
    DateTime firstofMonth = new DateTime(startDate.Year, startDate.Month, 1);
    DateTime endOfMonth = firstofMonth.AddMonths(1).AddDays(-1);