C# 获取给定周、年、月的开始和结束日期&;给定星期
如何在c#4.0中获取给定年份(int)、给定月份(int)和给定周(int){示例年份:2011月份:07周:04}的开始和结束日期?提前谢谢C# 获取给定周、年、月的开始和结束日期&;给定星期,c#,.net,c#-4.0,C#,.net,C# 4.0,如何在c#4.0中获取给定年份(int)、给定月份(int)和给定周(int){示例年份:2011月份:07周:04}的开始和结束日期?提前谢谢 2011年的开始日期是07月,该月的周数是04。不确定,但这就是你想要的吗 var weekStart = new DateTime(year, month, 1).AddDays(week * 7); var weekEnd = weekStart.AddDays(6); 他是你的朋友 月份: public DateTime FirstDayOfM
2011年的开始日期是07月,该月的周数是04。不确定,但这就是你想要的吗
var weekStart = new DateTime(year, month, 1).AddDays(week * 7);
var weekEnd = weekStart.AddDays(6);
他是你的朋友
月份:
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);
并且需要使用CultureInfo.FirstDay(或者任何您想要设置为一周的第一天的内容,在某些国家,这是星期一,有时是星期天)
//
///返回指定日期所在周的第一天
///日期在使用当前区域性中。
///
公共静态DateTime GetFirstDayOfWeek(DateTime dayInWeek)
{
CultureInfo defaultCultureInfo=CultureInfo.CurrentCulture;
返回GetFirstDateOfWeek(dayInWeek,defaultCultureInfo);
}
///
///返回指定日期所在周的第一天
///他在。
///
公共静态DateTime GetFirstDayOfWeek(DateTime dayInWeek,CultureInfo CultureInfo)
{
DayOfWeek firstDay=cultureInfo.DateTimeFormat.FirstDayOfWeek;
DateTime firstDayInWeek=dayInWeek.Date;
while(firstDayInWeek.DayOfWeek!=第一天)
firstDayInWeek=firstDayInWeek.AddDays(-1);
每周第一天返回;
}
假设您从第1周开始:
var startDate = new DateTime(year, month, 1).AddDays((week - 1) * 7);
var endDate = startDate.AddDays(6);
你也可以使用
DateTime.DaysInMonth(int year,int month);
去弄清楚。这几周将更加困难。日期时间的计算,因为这些计算有点棘手,通过一些假设,我可以得出这个结论
//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
当“一周”开始时,你的规则是什么?有很多可能性,等等。您的问题是“给定年、月和周数,如何获取一周的开始和结束日期?”???我不明白一年的开始和结束日期意味着什么。不是只有1月1日和12月31日吗?如果这是您的问题,请参阅以下内容:有用的代码片段,但我认为它与原始问题毫无关系(我想您可以使用FirstDayOfMonthFromDateTime())。
//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