在月末从数据库获取每周生日的问题

时间:2014-12-07 17:15:02

标签: c#

我有一个程序,每周显示成员的每周生日。此代码工作正常,直到月底。每当我们到达月末并且当前月份还剩下不到7天时,代码将不再列出生日。

我知道这是因为这一周现在已经持续了两个月,但我已经尝试了所有方法,但我无法弄清楚我必须做些什么才能解决这个问题。这可能是一个简单的问题。任何帮助将不胜感激。这是我的代码:

public void CheckDayOfWeekAndReturnBirthdaysInDateRange()
    {
        //Check the current day of the week and make calculations according to find out which week to use.
        if (DateTime.Now.DayOfWeek.ToString() == "Sunday")
        {
            DateTime weekStart = DateTime.Now.Date;
            DateTime weekEnd = DateTime.Now.AddDays(7);

            Birthdays = eventsService.ReturnBirthdaysForCurrentWeek(weekStart, weekEnd);
        }
        else if (DateTime.Now.DayOfWeek.ToString() == "Monday")
        {
            DateTime weekStart = DateTime.Now.AddDays(-1);
            DateTime weekEnd = DateTime.Now.AddDays(6);

            Birthdays = eventsService.ReturnBirthdaysForCurrentWeek(weekStart, weekEnd);
        }
        else if (DateTime.Now.DayOfWeek.ToString() == "Tuesday")
        {
            DateTime weekStart = DateTime.Now.AddDays(-2);
            DateTime weekEnd = DateTime.Now.AddDays(5);

            Birthdays = eventsService.ReturnBirthdaysForCurrentWeek(weekStart, weekEnd);
        }
        else if (DateTime.Now.DayOfWeek.ToString() == "Wednesday")
        {
            DateTime weekStart = DateTime.Now.AddDays(-3);
            DateTime weekEnd = DateTime.Now.AddDays(4);

            Birthdays = eventsService.ReturnBirthdaysForCurrentWeek(weekStart, weekEnd);
        }
        else if (DateTime.Now.DayOfWeek.ToString() == "Thursday")
        {
            DateTime weekStart = DateTime.Now.AddDays(-4);
            DateTime weekEnd = DateTime.Now.AddDays(3);

            Birthdays = eventsService.ReturnBirthdaysForCurrentWeek(weekStart, weekEnd);
        }
        else if (DateTime.Now.DayOfWeek.ToString() == "Friday")
        {
            DateTime weekStart = DateTime.Now.AddDays(-5);
            DateTime weekEnd = DateTime.Now.AddDays(2);

            Birthdays = eventsService.ReturnBirthdaysForCurrentWeek(weekStart, weekEnd);
        }
        else if (DateTime.Now.DayOfWeek.ToString() == "Saturday")
        {
            DateTime weekStart = DateTime.Now.AddDays(-6);
            DateTime weekEnd = DateTime.Now.AddDays(1);

            Birthdays = eventsService.ReturnBirthdaysForCurrentWeek(weekStart, weekEnd);
        }
    }

    public void LoadDatagridComponents(DataGridView dataBirthdays)
    {
        dataBirthdays.AutoGenerateColumns = false;
        dataBirthdays.Columns[0].Visible = true;
        dataBirthdays.Columns[1].Visible = true;
        dataBirthdays.Columns[2].Visible = true;

        dataBirthdays.Columns[0].HeaderText = "Name";
        dataBirthdays.Columns[1].HeaderText = "Surname";
        dataBirthdays.Columns[2].HeaderText = "Birthday";

        //Loop through each birthday member and change date of birth to month/day fromat.
        int currentRow = 0;
        foreach (DataGridViewRow row in dataBirthdays.Rows)
        {
            string birthday = Convert.ToDateTime(dataBirthdays.Rows[currentRow].Cells[2].Value).ToString("MMMM dd");
            dataBirthdays.Rows[currentRow].Cells[2].Value = birthday;
            currentRow++;
        }
    }

然后从那里开始:

public List<Birthdays> ReturnBirthdaysForCurrentWeek(DateTime weekStart, DateTime weekEnd)
    {
        var birthdays = new List<Birthdays>();

        int month = DateTime.Now.Month;
        int dayStartOfWeek = weekStart.Day;
        int dayEndOfWeek = weekEnd.Day;

        using (MySqlConnection Conn = new MySqlConnection(Connect.sConnStr))
        {
            Conn.Open();
            string sSql = "SELECT name, surname, date_birth FROM members WHERE MONTH(date_birth) = " + month + " AND DAY(date_birth) BETWEEN " + dayStartOfWeek + " AND " + dayEndOfWeek + ";";

            MySqlDataReader reader = Connect.getDataCommand(sSql, Conn).ExecuteReader();

            while (reader.Read())
            {
                var birthday = new Birthdays()
                {
                    MemberName = reader["name"].ToString(),
                    MemberSurname = reader["surname"].ToString(),
                    MemberBirthday = reader["date_birth"].ToString()
                };
                birthdays.Add(birthday);
            }

            Conn.Close();
            Conn.Dispose();
        }
        return birthdays;
    }

1 个答案:

答案 0 :(得分:1)

为什么不直接比较日期,而不是将日期比较逻辑分解为月和日比较(有你发现的错误),为什么不直接比较日期呢?

例如,这可以通过sql参数完成:

string sSql = "SELECT name, surname, date_birth FROM members WHERE date_birth BETWEEN @param_val_1 AND @param_val_2";
MySqlCommand command = Connect.getDataCommand(sSql, Conn);
command.Parameters.AddWithValue("@param_val_1", weekStart);
command.Parameters.AddWithValue("@param_val_2", weekEnd);

您还可以简化代码以获取“当前”周,以避免所有案例逻辑:

var today = DateTime.Today;
// start with the numbers [0 .. 7)
var startOfWeek = Enumerable.Range(0, count: 7)
    // for each, subtract that many days from today
    .Select(i => today.AddDays(-i))
    // find the first such date that is a Sunday
    .First(dt => dt.DayOfWeek == DayOfWeek.Sunday);
var endOfWeek = startOfWeek.AddDays(6);

根据您存储数据的方式,您可能还需要注意时间组件。 DateTime.Today为您提供当前没有时间组件的日子(例如当天的午夜)。但是,如果数据库中的日期具有其他时间组件,则可能需要调整逻辑以考虑这些组件。