获取给定周年的开始和结束日期,给定月份和时间。给了一周

时间:2011-07-29 10:54:24

标签: c# .net c#-4.0

如何在c#4.0中获取给定年份(int),给定月份(int)和给定周期(int){示例年份:2011月份:07周:04}的开始和结束日期?提前谢谢。

2011年07月的开始日期和月份的周数是04。

5 个答案:

答案 0 :(得分:9)

Google是你的朋友。

个月:

public DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
   return new DateTime(dateTime.Year, dateTime.Month, 1);
}


public DateTime LastDayOfMonthFromDateTime(DateTime dateTime)
{
   DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
   return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
}

多年来你可以做类似的事情:

   DateTime time = new DateTime(2011,1,1);
   time.AddYears(1).AddDays(-1);

并且week需要使用CultureInfo.FirstDay(或者您想要设置为一周的第一天,在某些国家/地区是星期一,有时是星期天)。

/// <summary>
    /// Returns the first day of the week that the specified
    /// date is in using the current culture. 
    /// </summary>
    public static DateTime GetFirstDayOfWeek(DateTime dayInWeek)
    {
        CultureInfo defaultCultureInfo = CultureInfo.CurrentCulture;
        return GetFirstDateOfWeek(dayInWeek, defaultCultureInfo);
    }

    /// <summary>
    /// Returns the first day of the week that the specified date 
    /// is in. 
    /// </summary>
    public static DateTime GetFirstDayOfWeek(DateTime dayInWeek, CultureInfo cultureInfo)
    {
        DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;
        DateTime firstDayInWeek = dayInWeek.Date;
        while (firstDayInWeek.DayOfWeek != firstDay)
            firstDayInWeek = firstDayInWeek.AddDays(-1);

        return firstDayInWeek;
    }

答案 1 :(得分:0)

不确定,但这就是你所追求的吗?

var weekStart = new DateTime(year, month, 1).AddDays(week * 7);
var weekEnd = weekStart.AddDays(6);

答案 2 :(得分:0)

假设你从第1周开始:

var startDate = new DateTime(year, month, 1).AddDays((week - 1) * 7);
var endDate = startDate.AddDays(6);

答案 3 :(得分:0)

您也可以使用

DateTime.DaysInMonth(int year,int month);

弄清楚。这几周将更加困难。

答案 4 :(得分:0)

DateTime计算因为这些有点棘手,我可以想出一些假设

//assign it to the first day of the month
DateTime getweek = new DateTime(2011, 4, 1);
// say the week starts on a Sunday
while (getweek.DayOfWeek != DayOfWeek.Sunday)
      getweek = getweek.AddDays(1);
DateTimeFormatInfo info = DateTimeFormatInfo.CurrentInfo;            
Calendar cal = info.Calendar;
//Now you are on the first week add 3 more to move to the Fourth week
DateTime start = cal.AddWeeks(getweek, 3); // 24 April 2011
DateTime end = start.AddDays(6); // 30 April 2011