1 using System; 2 3 namespace ConsoleAppDemo 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 DateTime now = DateTime.Now; 10 Console.WriteLine($"First Day Of Month:{now.FirstDayOfMonth()}"); 11 Console.WriteLine($"Last Day Of Month:{now.LastDayOfMonth()}"); 12 Console.WriteLine($"First Day Of Previous Month:{now.FirstDayOfPreviousMonth()}"); 13 Console.WriteLine($"Last Day Of Previous Month:{now.LastDayOfPreviousMonth()}"); 14 Console.WriteLine($"First Day Of Previous Week:{now.FirstDayOfPreviousWeek()}"); 15 Console.WriteLine($"Last Day Of Previous Week:{now.LastDayOfPreviousWeek()}"); 16 Console.ReadKey(); 17 } 18 } 19 20 public static class DateTimeExtension 21 { 22 /// 取得某月的第一天 23 /// </summary> 24 /// <param name="datetime">要取得月份第一天的时间</param> 25 /// <returns></returns> 26 public static DateTime FirstDayOfMonth(this DateTime datetime) 27 { 28 return datetime.AddDays(1 - datetime.Day); 29 } 30 /// <summary> 31 /// 取得某月的最后一天 32 /// </summary> 33 /// <param name="datetime">要取得月份最后一天的时间</param> 34 /// <returns></returns> 35 public static DateTime LastDayOfMonth(this DateTime datetime) 36 { 37 return FirstDayOfMonth(datetime).AddMonths(1).AddDays(-1); 38 } 39 40 /// <summary> 41 /// 取得上个月第一天 42 /// </summary> 43 /// <param name="datetime">要取得上个月第一天的当前时间</param> 44 /// <returns></returns> 45 public static DateTime FirstDayOfPreviousMonth(this DateTime datetime) 46 { 47 return FirstDayOfMonth(datetime).AddMonths(-1); 48 } 49 50 /// <summary> 51 /// 取得上个月的最后一天 52 /// </summary> 53 /// <param name="datetime">要取得上个月最后一天的当前时间</param> 54 /// <returns></returns> 55 public static DateTime LastDayOfPreviousMonth(this DateTime datetime) 56 { 57 return FirstDayOfMonth(datetime).AddDays(-1); 58 } 59 60 /// <summary> 61 /// 取得上周的第一天 62 /// </summary> 63 /// <param name="datetime">要取得上周第一天的当前时间</param> 64 /// <returns></returns> 65 public static DateTime FirstDayOfPreviousWeek(this DateTime datetime) 66 { 67 return LastDayOfPreviousWeek(datetime).AddDays(-6); 68 } 69 70 /// <summary> 71 /// 取得上周的最后一天 72 /// </summary> 73 /// <param name="datetime">要取得上周最后一天的当前时间</param> 74 /// <returns></returns> 75 public static DateTime LastDayOfPreviousWeek(this DateTime datetime) 76 { 77 int dayOfWeek = (int)datetime.DayOfWeek; 78 return datetime.AddDays(dayOfWeek == 0 ? -7 : -dayOfWeek); 79 } 80 } 81 82 }