C# 关于获取周,月,年时间,日期格式化

           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();

结果如图所示:

二、日期格式转换

  符号       语法   示例(2016-05-09 13:09:55:2350) 格式说明
y DateTime.Now.ToString() 2016/5/9 13:09:55 短日期 长时间
d DateTime.Now.ToString("d") 2016/5/9 短日期
D DateTime.Now.ToString("D") 2016年5月9日 长日期
f DateTime.Now.ToString("f") 2016年5月9日 13:09 长日期 短时间
F DateTime.Now.ToString("F") 2016年5月9日 13:09:55 长日期 长时间
g DateTime.Now.ToString("g") 2016/5/9 13:09 短日期 短时间
G DateTime.Now.ToString("G")  2016/5/9 13:09:55 短日期 长时间
t DateTime.Now.ToString("t") 13:09 短时间
T DateTime.Now.ToString("T") 13:09:55 长时间
u DateTime.Now.ToString("u") 2016-05-09 13:09:55Z  
U DateTime.Now.ToString("U") 2016年5月9日 5:09:55 本初子午线的长日期和长时间
m DateTime.Now.ToString("m") 5月9日  
M DateTime.Now.ToString("M") 5月9日  
r DateTime.Now.ToString("r") Mon, 09 May 2016 13:09:55 GMT  
R DateTime.Now.ToString("R") Mon, 09 May 2016 13:09:55 GMT  
y DateTime.Now.ToString("y") 2016年5月  
Y DateTime.Now.ToString("Y") 2016年5月  
o DateTime.Now.ToString("o") 2016-05-09T13:09:55.2350000  
O DateTime.Now.ToString("O") 2016-05-09T13:09:55.2350000         
s DateTime.Now.ToString("s") 2016-05-09T13:09:55
原文地址:https://www.cnblogs.com/ElvisZhongShao/p/9994954.html