[.net]取得本週本月次月下月的第一天最後一天

  • 127
  • 0

[.net]取得本週本月次月下月的第一天最後一天

void Main()
{
	Console.WriteLine(DateTime.Now.FirstDayOfWeek());
	Console.WriteLine(DateTime.Now.LastDayOfWeek());
	Console.WriteLine(DateTime.Now.FirstDayOfLastMonth());
	Console.WriteLine(DateTime.Now.LastDayOfLastMonth());
	Console.WriteLine(DateTime.Now.FirstDayOfMonth());
	Console.WriteLine(DateTime.Now.LastDayOfMonth());
	Console.WriteLine(DateTime.Now.FirstDayOfNextMonth());
	Console.WriteLine(DateTime.Now.LastDayOfNextMonth());

}

// Define other methods and classes here
public static partial class DateTimeExtensions
{
	//每週第一天(週日)
	public static DateTime FirstDayOfWeek(this DateTime dt)
	{
		var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
		var diff = dt.DayOfWeek - culture.DateTimeFormat.FirstDayOfWeek;

		if (diff < 0)
		{
			diff += 7;
		}

		return dt.AddDays(-diff).Date;
	}

	//每週最後一天(週六)
	public static DateTime LastDayOfWeek(this DateTime dt) =>
		dt.FirstDayOfWeek().AddDays(6);

	//上個月第一天
	public static DateTime FirstDayOfLastMonth(this DateTime dt) =>
		new DateTime(dt.AddMonths(-1).Year, dt.AddMonths(-1).Month, 1);

	//上個月最後一天
	public static DateTime LastDayOfLastMonth(this DateTime dt) =>
		dt.FirstDayOfLastMonth().AddMonths(1).AddDays(-1);

	//每個月第一天
	public static DateTime FirstDayOfMonth(this DateTime dt) =>
		new DateTime(dt.Year, dt.Month, 1);

	//每個月最後一天
	public static DateTime LastDayOfMonth(this DateTime dt) =>
		dt.FirstDayOfMonth().AddMonths(1).AddDays(-1);

	//下個月第一天
	public static DateTime FirstDayOfNextMonth(this DateTime dt) =>
		dt.FirstDayOfMonth().AddMonths(1);

	//下個月最後一天
	public static DateTime LastDayOfNextMonth(this DateTime dt) =>
		dt.FirstDayOfNextMonth().AddMonths(1).AddDays(-1);
}


執行結果:(這是linqpad執行結果截圖)