编程语言
首页 > 编程语言> > C# -- 获取日期

C# -- 获取日期

作者:互联网

static void Main(string[] args)
        {
            DateTime now = DateTime.Now;

            DayOfWeek dayOfWeek = now.DayOfWeek;
            int daysWeek = dayOfWeek == DayOfWeek.Sunday ? 7 : (int)dayOfWeek;
            //本周第一天(此结果是周一,如果想要结果是周日的,不用+1)
            DateTime thisWeekFirstDay = now.AddDays(daysWeek + 1);
            Console.WriteLine(thisWeekFirstDay);

            //本月第一天
            DateTime thisMonthFirstDay = now.AddDays(now.Day + 1);
            Console.WriteLine(thisMonthFirstDay);

            //本年第一天
            DateTime thisYearFirstDay = now.AddMonths(now.Month + 1).AddDays(now.Day + 1);
            Console.WriteLine(thisYearFirstDay);

            //上周第一天(此结果是周一,如果想要结果是周日的,不用+1)
            DateTime lastWeekFrstDay = now.AddDays(daysWeek - 7 + 1);
            Console.WriteLine(lastWeekFrstDay);

            //上周最后一天
            DateTime lastWeekLastdDay = now.AddDays(daysWeek);
            Console.WriteLine(lastWeekLastdDay);

            //上月第一天
            DateTime lastMonthFirstday = now.AddMonths(-1).AddDays(now.Day + 1);
            Console.WriteLine(lastWeekLastdDay);

            //上月最后一天
            DateTime lastMonthLastday = now.AddDays(now.Day);
            Console.WriteLine(lastMonthLastday);

            //上年第一天
            DateTime lastYearFirstDay = now.AddYears(-1).AddMonths(now.Month + 1).AddDays(now.Day + 1);
            Console.WriteLine(lastYearFirstDay);

            //上年最后一天
            DateTime lastYearLastDay = now.AddMonths(now.Month + 1).AddDays(now.Day);
            Console.WriteLine(lastYearLastDay);

            Console.ReadLine();
        }

 

标签:Console,C#,AddDays,DateTime,获取,日期,WriteLine,now,Day
来源: https://www.cnblogs.com/dcy521/p/11676262.html