在 C# 中获取给定月份和年份的最后日期
本文关键字:最后 日期 获取 | 更新日期: 2023-09-27 18:32:01
我想要 C# 代码来获取给定月份和年份的一周最后日期。
假设给定的月份是 1,年份是 2016,那么方法应该返回我
--01/02/2016
--01/09/2016
--01/16/2016
--01/23/2016
--01/30/2016
--02/06/2016
所以你需要一个以一年和一个月作为参数并返回日期的方法。这些日期应该是该月所有周的最后日期,也可以选择是后续月份的最后日期。
这应该有效,然后:
public static IEnumerable<DateTime> GetLastWeekDatesOfMonth(int year, int month, DayOfWeek firstDayOfWeek = DayOfWeek.Monday, bool includeLaterMonths = false)
{
DateTime first = new DateTime(year, month, 1);
int daysOffset = (int)firstDayOfWeek - (int)first.DayOfWeek;
if (daysOffset < 0)
daysOffset = 7 - Math.Abs(daysOffset);
DateTime firstWeekDay = first.AddDays(daysOffset);
DateTime current = firstWeekDay.AddDays(-1); // last before week start
if (current.Month != month)
current = current.AddDays(7);
yield return current;
if (includeLaterMonths)
{
while (true)
{
current = current.AddDays(7);
yield return current;
}
}
else
{
while((current = current.AddDays(7)).Month == month)
yield return current;
}
}
您的样品:
var lastDates = GetLastWeekDatesOfMonth(2016, 1, DayOfWeek.Sunday, true);
foreach (DateTime dt in lastDates.Take(6))
Console.WriteLine(dt.ToShortDateString());
public static DateTime GetLastDateofWeek(int yr, int mnth, int week) { 日期时间 dt = new DateTime(yr, mnth, 1); 日期时间新日期 = 新日期时间(); 如果(分。星期几 == 星期几.星期一) { 新日期 = DT。添加天数(((周 - 1) * 7) + 5); } 还 { 新日期 = DT。AddDays((8 - (int)dt.星期几) % 7 + ((周 - 2) * 7) + 5); } 返回新日期; }
首先获取月份和年份,例如:
int year = 2016;
int month = 1;
然后创建表示第一个星期六的 DateTime 类的新实例。
DateTime firstsaturday = new DateTime(year,month,1);
while(firstsaturday.DayOfWeek != DayOfWeek.Saturday)
{
firstsaturday = firstsaturday.AddDays(1);
]
然后创建日期时间值列表。
List<DateTime> saturdays = new List<DateTime>();
saturdays.Add(firstsaturday);
然后使用循环循环遍历所有星期六。
DateTime CurrentSaturday = firstsaturday;
while(CurrentSaturday.AddDays(7).Month == month)
{
CurrentSaturday = CurrentSaturday.AddDays(7);
Saturdays.Add(CurrentSaturday);
}
你可以试试这段代码。
using System;
public class Program
{
public static void Main()
{
DateTime thisMonthInLastYear = DateTime.Now.AddYears(-1);
DateTime endOfMonth = new DateTime(thisMonthInLastYear.Year,
thisMonthInLastYear.Month,
DateTime.DaysInMonth(thisMonthInLastYear.Year,
thisMonthInLastYear.Month));
Console.WriteLine("Today : "+DateTime.Now.ToString("dd-MM-yyyy"));
Console.WriteLine("This Month in last years : "+endOfMonth.ToString("dd-MM-yyyy"));
Console.WriteLine("Next month in last years : "+endOfMonth.AddMonths(1).ToString("dd-MM-yyyy"));
}
}