我如何从一周开始约会,也参加53周的工作? C#

时间:2010-03-29 10:36:10

标签: c# datetime date week-number

我已经做了一个功能,可以在一年内完成这几周,而且工作正常。问题是我需要一种方法来获得本周的星期一。这是一个瑞典日历。

以下代码适用于有52周的年份,但有些年份(如2009年)有53周。然后我从januari得到一个约会作为mondaydate(不能是正确的)。所以,请帮助我让它工作多年。

我可能做的是检查一年是否有53周然后做一些检查,但我希望它没有特别检查就能顺利进行。

以下是我的想法:

    public static DateTime GetDateFromWeek(int year, int week)
    {
        //First day of the year
        DateTime d = new DateTime(year, 1, 1);
        GregorianCalendar calendar = new GregorianCalendar(GregorianCalendarTypes.MiddleEastFrench);
        d = calendar.AddWeeks(d, week);
        d = d.AddDays(1 - (double)d.DayOfWeek);
        return d;
    }

4 个答案:

答案 0 :(得分:4)

我认为您的基本问题是假设DateTime d = new DateTime(year, 1, 1);在一年的第一周,但它可能属于上一年的第52/53周。

您将找到解决方案here

答案 1 :(得分:2)

这应该这样做:

public static DateTime GetDateFromWeek(int year, int week)
{
    GregorianCalendar calendar = new GregorianCalendar(GregorianCalendarTypes.MiddleEastFrench);
    DateTime d = new DateTime(year, 12, 31);
    int weeksInYear = calendar.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
    int weeksToSubtract = weeksInYear - week;
    d = calendar.AddWeeks(d, -weeksToSubtract);
    d = d.AddDays(1 - (int)d.DayOfWeek);
    return d;
}

答案 2 :(得分:0)

您可能想看一下以下问题,我认为这就是您要问的问题:

Get date of first Monday of the week?

答案 3 :(得分:-1)

if (cmb_mode_of_service.SelectedItem.ToString() == "Weekly Service")
            {
                int year = 0;
                if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                {
                    year = 1;
                }

                if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                {
                    year = 2;
                }

                if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                {
                    year = 3;
                }

                DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                DateTime Enddate = currentdate.AddYears(+year);


                char c1 = 'A';
                int c2 = 1;
                for (var dt1 = currentdate; dt1 <= Enddate; dt1 = dt1.AddDays(7))
                {
                    DataRow dr = dt.NewRow();
                    dr["SN"] = c2++;
                    dr["serviceid"] = "S4-" + c1++;
                    dr["servicedate"] = dt1.ToString();
                    dr["servicestatus"] = "Pending";
                    dr["serviceexcutive"] = "Not Alowed";
                    dt.Rows.Add(dr);

                }
                dataGridView1.DataSource = dt;

            }