如何使用整数值确定星期几,使用另一个整数确定星期几?例如,如果今天是(为星期天输入一个类似0的整数),而我则输入整数2,则其为星期二。这是我到目前为止的代码:
namespace DayOfTheWeek
{
class Program
{
static void Main(string[] args)
{
int Sunday=0;
int Monday = 1;
int Tuesday = 2;
int Wednesday = 3;
int Thursday = 4;
int Friday = 5;
int Saturday = 6;
Console.WriteLine("Today is " + 0);
}
}
}
我真的很沮丧。
答案 0 :(得分:5)
您可以为此使用数组:
string[] daysOfWeek = new string[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
int dayVal = 2;
if (dayVal >= 0 && dayVal < daysOfWeek.Length) // check it's within the bounds of the array, we don't want any IndexOutOfBounds exceptions being thrown for bad user input
{
Console.WriteLine($"Today is {daysOfWeek[dayVal]}.")
}
或者,您可以使用字典:
Dictionary<int, string> daysOfWeek = new Dictionary<int, string>()
{
{ 0, "Sunday" },
{ 1, "Monday" },
{ 2, "Tuesday" },
{ 3, "Wednesday" },
{ 4, "Thursday" },
{ 5, "Friday" },
{ 6, "Saturday" }
};
int dayVal = 2;
if (daysOfWeek.TryGetValue(dayVal, out string dayName)) // check it's in the dictionary and retrieve the result
{
Console.WriteLine($"Today is {dayName}.");
}
或者您可以创建一个枚举(由于.NET已经有这样的枚举,因此您无需在一周中的几天内使用该枚举):
public enum DaysOfWeek
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6
}
int dayVal = 2;
if (Enum.IsDefined(typeof(DaysOfWeek), dayVal)) // check it's in the enum
{
var dayOfWeek = (DaysOfWeek)dayVal;
Console.WriteLine($"Today is {dayOfWeek}."); // this will print the name corresponding to the enum value
}
并改为使用内置的.NET DayOfWeek枚举:
int dayVal = 2;
if (Enum.IsDefined(typeof(DayOfWeek), dayVal)) // check it's in the enum
{
var dayOfWeek = (DayOfWeek)dayVal;
Console.WriteLine($"Today is {dayOfWeek}."); // this will print the name corresponding to the enum value
}
要确定一周的第二天,您应该使用以下代码:
int nextDay = dayVal == 6 ? 0 : dayVal + 1;
请注意以下一种替代方法:
DateTime today = DateTime.Now.Date;
Console.WriteLine($"Today is {today.DayOfWeek}.");
DateTime tomorrow = today.AddDays(1);
Console.WriteLine($"Tomorrow is {tomorrow.DayOfWeek}.");