我正在使用c#创建日记应用程序。我有一个datagridview,我想从本周开始的每年的每个星期一显示一年。下面是我到目前为止的代码:
//Loop which goes through every Monday 50 times, therefore it displays every Monday for a year on the users profile.
int x = 0;
do
{
x = x + 1;
string monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday).ToString("dd-MM-yyyy");
metroDataGrid1.Rows.Add(monday);
}
while (x < 50);
//After 50 weeks have been displayed it will reset the count to 0.
if(x == 50)
{
x = 0;
}
foreach (DataGridViewRow row in metroDataGrid1.Rows)
{
row.Height = 60;
}
我才刚刚开始学习c#,因此为什么这可能是遥不可及的...
当前,它在DGV中显示当前星期一(每周50次)。见下文:
我需要它以dd / MM / yyyy格式显示下一年的每个星期一。例如 18/11/2019 25/11/2019 2019/02/12 2019/09/12 16/12/2019 ...
感谢您的帮助。
答案 0 :(得分:0)
每个步骤都从DateTime.Today开始。取而代之的是,您可以执行类似的操作,但是使用代码来查找星期一,而不是使用Today。
var currentMonday = DateTime.Today;
do
{
monday = currentMonday.ToString();
currentMonday = currentMonday.AddDays(7);
}
答案 1 :(得分:0)
因此,首先,如果要格式化日期,则可以将toString与相应的参数一起使用。看到这里:https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
如果您需要一年中的所有星期一,可以尝试以下方法:
static void Main(string[] args)
{
var monday = FirstMondayOfYear(2019);
var lastDay = new DateTime(2019, 12, 31);
for (var currentMonday = monday; currentMonday.CompareTo(lastDay) <= 0; currentMonday = currentMonday.AddDays(7))
{
Console.WriteLine(currentMonday.ToString("dd/MM/yyyy"));
//Add it to your list or whatever
}
Console.ReadKey();
}
public static DateTime FirstMondayOfYear(int year)
{
var tmp = new DateTime(year - 1, 12, 30);
return tmp.AddDays(8-(int)tmp.DayOfWeek);
}
请不要说我使用了for循环而不是do while(我更喜欢这样,因为它很明显: -输入(周一开始) -检查(该年当前仍是星期一) -增量(到当前星期一增加7天)
CompareTo将当前的星期一与lastDate进行比较(将其设置为您要获取其“星期一”的最大日期)。如果currentMonday在lastDay之前,则CompareTo将返回-1;如果相等,则返回0;如果currentMonday在lastDay之后,则返回1。