Question

i have database from which i get data to my C# app using SQL query.

I have option in my app which get data for current day selected from MonthCalendar:

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

so when i select 2012-03-06 from my calendar form i get something like this for my sql query:

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

And it's working.

Now i'd like to get data for entire month - how to modify part of sql query so when i select day in April i get this:

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

?

EDIT: I make some progress - I have first day of month, but how to get last?

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

Solution

Never put your SQL statements together as strings! Remember Bobby tables...

Apart from that:

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);
    ...
}

EDIT
Come to think of it: You'll actually notice that what you want will not return any entries that are between lastOfMonth 00:00:01 and lastOfMonth 23:59:59. Actually, you should query from the first of the selected month to the first of the following month to get the desired information (subtracting one Millisecond instead of one Day won't help, as SQL Server can not store milliseconds extactly).

OTHER TIPS

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")+

use this to get last day of the selected month

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top