C#中时间相关知识点小结
C#中时间相关知识点小结
一、月份英文简写
DateTime dt = DateTime.Now; string MM = dt.AddMonths(-1).ToString("MMM", new System.Globalization.CultureInfo("en-us"));//月英文缩写:Jul
二、当月第一天和最后一天
DateTime ThisMonth_Frist = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date; DateTime ThisMOnth_Last = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1);
三、上月第一天和最后一天
DateTime Today = DateTime.Today;//当天时间 DateTime ThisMonth = new DateTime(Today.Year, Today.Month, 1);//当前月第一天时间 DateTime LastMonth_First = ThisMonth.AddMonths(-1);//上月第一天时间 DateTime LastMonth_Last = ThisMonth.AddDays(-1);//上月最后一天时间
四、本周第几天
int daysInWeek1 = (int)DateTime.Now.DayOfWeek;//注意:此处周,日时返回0, int daysInWeek2 = (int)DateTime.Now.DayOfWeek == 0 ? 7 : (int)DateTime.Now.DayOfWeek;//当前周第几天,注释:周日为0
五、本月第几周
int a = WeekOfMonth(DateTime.Now, false);//
六、本年第几周
private int WeekOfYear() { var dt = DateTime.Now; int firstWeekend = Convert.ToInt32(DateTime.Parse(dt.Year + "-1-1").DayOfWeek); int weekDay = firstWeekend == 0 ? 1 : (7 - firstWeekend + 1); int currentDay = dt.DayOfYear; int current_week = Convert.ToInt32(Math.Ceiling((currentDay - weekDay) / 7.0)) + 1; return current_week; }
七、前几周的周一和周日
private void FEDayInLastWeek() { int N = 3;//前几周参数 DateTime Today = DateTime.Now; int daysInWeek = (int)Today.DayOfWeek == 0 ? 7 : (int)Today.DayOfWeek;//当前周第几天,注释:周日为0 for (int i = N; i > 0; i--) { //起始日期 DateTime firstDay = Today.AddDays(1 - (7 * i + daysInWeek)); DateTime lastDay = Today.AddDays(7 - (7 * i + daysInWeek)); } }
八、本周一和当前日
private void FristDayToNowInThisWeek() { int daysInWeek = (int)DateTime.Now.DayOfWeek == 0 ? 7 : (int)DateTime.Now.DayOfWeek;//当前周第几天,注释:周日为0 //起始日期 DateTime firstDay = DateTime.Now.AddDays(1 - daysInWeek); DateTime lastDay = DateTime.Now; }
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/14963113.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。