而不是指定 “ string [] week_Days = {” Monday“,” Tuesday“ ...};”
如何动态地将天设置为数组?
我尝试解决此问题,但无法以“星期日”作为开始日期-
DateTime days = DateTime.Now;
string[] weekDays = new string[7];
for (int i = 0; i < weekDays.Length; i++)
{
weekDays[i] = string.Format("{0:dddd}", days.AddDays(i));
Console.WriteLine(weekDays[i]);
days = DateTime.Now;
}
输出-
Wednesday
Thursday
Friday
Saturday
Sunday
Monday
Tuesday
答案 0 :(得分:1)
您可以使用此LINQ查询。唯一的挑战是获得正确的订单:
DayOfWeek firstWeekDay = DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek;
string[] weekDays = Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>()
.OrderBy(dow => dow < firstWeekDay ? 7-(int)dow : dow-firstWeekDay)
.Select(dow => dow.ToString())
.ToArray();
也许某人比OrderBy
更优雅。
答案 1 :(得分:1)
using System;
using System.Globalization;
static void Main()
{
string[] weekDays = new CultureInfo("en-us").DateTimeFormat.DayNames;
for (int i = 1; i <= 7; i++)
Console.WriteLine(weekDays[i % 7]);
}
答案 2 :(得分:0)
您可以使用DayOfWeek枚举:
string[] weekdays = Enum.GetNames(typeof(DayOfWeek));
编辑:如果您需要更改一周的开始日期:
private static string[] GetWeekdays(DayOfWeek firstDayOfWeek)
{
string[] weekdays = new string[7];
DateTime dateTime = DateTime.Now;
while (dateTime.DayOfWeek != firstDayOfWeek)
{
// Find the next date with start day of week
dateTime = dateTime.AddDays(1);
}
for (int i = 0; i < 7; i++)
{
// Get day of week of current day, add 1 day, iterate 7 times.
weekdays[i] = dateTime.DayOfWeek.ToString();
dateTime = dateTime.AddDays(1);
}
return weekdays;
}
答案 3 :(得分:0)
string[] week_Days = new string[7];
DayOfWeek day = DayOfWeek.Sunday;
for (int i = 0; i < week_Days.Length; i++)
{
week_Days[i] = day.ToString();
Console.WriteLine(week_Days[i]);
day++;
}
使用DayOfWeek代替分配DateTime属性。可以轻松解决问题。
答案 4 :(得分:0)
您的代码失败,因为DateTime.Now
并不总是在星期日:
DateTime days = DateTime.Now;
最好使用现有的DayOfWeek
枚举:
string[] weekdays = Enum.GetNames(typeof(DayOfWeek));
答案 5 :(得分:0)
这也可以通过这种方式完成。在获得“星期一”之前,将日期添加到DateTime.Now中。
int j = 0;
string[] weekDays = new string[7];
DateTime days = DateTime.Now;
while (weekDays[0] != "Sunday")
{
days = days.AddDays(j++);
weekDays[0] = string.Format("{0:dddd}", days);
if (weekDays[0] != "Sunday")
days = DateTime.Now;
}
for (int i = 0; i < weekDays.Length; i++)
{
weekDays[i] = string.Format("{0:dddd}", days.AddDays(i));
Console.WriteLine(weekDays[i]);
}
答案 6 :(得分:-1)
Console.WriteLine(new System.Globalization.CultureInfo("en-us").DateTimeFormat.DayNames[byte.Parse(Console.ReadLine()) % 7]);