我一直在绞尽脑汁,但是星期五已经很晚了,我会围成一圈。
我需要为下拉列表创建一个工作周列表,并将周数作为值。所以代码会输出:
8月22日星期一 - 9月26日星期五 8月29日星期一 - 9月2日星期五 9月5日周一至9月9日周五
等。
全年。我有什么想法会实现这个目标吗?
感谢。
答案 0 :(得分:25)
我认为以下代码符合ISO 8601:
var jan1 = new DateTime(DateTime.Today.Year , 1, 1);
//beware different cultures, see other answers
var startOfFirstWeek = jan1.AddDays(1 - (int)(jan1.DayOfWeek));
var weeks=
Enumerable
.Range(0,54)
.Select(i => new {
weekStart = startOfFirstWeek.AddDays(i * 7)
})
.TakeWhile(x => x.weekStart.Year <= jan1.Year)
.Select(x => new {
x.weekStart,
weekFinish=x.weekStart.AddDays(4)
})
.SkipWhile(x => x.weekFinish < jan1.AddDays(1) )
.Select((x,i) => new {
x.weekStart,
x.weekFinish,
weekNum=i+1
});
答案 1 :(得分:3)
请记住,那个星期的计算在不同文化中的表现方式不同,如果你看到第53周,就没有错误!
using System.Globalization;
CultureInfo cultInfo = CultureInfo.CurrentCulture;
int weekNumNow = cultInfo.Calendar.GetWeekOfYear(DateTime.Now,
cultInfo.DateTimeFormat.CalendarWeekRule,
cultInfo.DateTimeFormat.FirstDayOfWeek);
答案 2 :(得分:3)
只需更新Spender的内容,因为我想让你的日期时间的输出更符合你想要的。
DateTime jan1 = new DateTime(DateTime.Today.Year, 1, 1);
//beware different cultures, see other answers
DateTime startOfFirstWeek = jan1.AddDays(1 - (int)(jan1.DayOfWeek));
var weeks=
Enumerable
.Range(0,54)
.Select(i => new {
weekStart = startOfFirstWeek.AddDays(i * 7)
})
.TakeWhile(x => x.weekStart.Year <= jan1.Year)
.Select(x => new {
x.weekStart,
weekFinish=x.weekStart.AddDays(4)
})
.SkipWhile(x => x.weekFinish.Year < jan1.Year)
.Select((x,i) => new {
WeekStart = x.weekStart.ToString("dddd, d, MMMM"),
WeekFinish = x.weekFinish.ToString("dddd, d, MMMM"),
weekNum=i+1
});
将格式更改为您想要的格式的更改是在匿名对象的最后一个选择中。
答案 3 :(得分:0)
您可能需要稍微调整一下,但它应该能满足您的需求:
static void Main(string[] args)
{
List<DateTime[]> weeks = new List<DateTime[]>();
DateTime beginDate = new DateTime(2011, 01, 01);
DateTime endDate = new DateTime(2012, 01, 01);
DateTime monday = DateTime.Today;
DateTime friday = DateTime.Today;
while (beginDate < endDate)
{
beginDate = beginDate.AddDays(1);
if (beginDate.DayOfWeek == DayOfWeek.Monday)
{
monday = beginDate;
}
else if (beginDate.DayOfWeek == DayOfWeek.Friday)
{
friday = beginDate;
}
else if (beginDate.DayOfWeek == DayOfWeek.Saturday)
{
weeks.Add(new DateTime[] { monday, friday });
}
}
for (int x = 0; x < weeks.Count; x++)
{
Console.WriteLine(weeks[x][0].Date.ToShortDateString() + " - " + weeks[x][1].Date.ToShortDateString());
}
Console.ReadLine();
}
答案 4 :(得分:0)
您可以使用Time Period Library for .NET的周类:
DateTime start = DateTime.Now.Date;
DatTime end = start.AddYears( 1 );
Week week = new Week( start );
while ( week.Start < end )
{
Console.WriteLine( "week " + week );
week = week.GetNextWeek();
}