Net Core教程

C#中时间相关知识点小结

本文主要是介绍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;
        }

 

这篇关于C#中时间相关知识点小结的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!