Getting first and last day of the current month

前端 未结 6 1135
独厮守ぢ
独厮守ぢ 2020-12-13 06:15

I have here 2 datepicker for start date and end date.

how can I get the first day and last day of the current month



        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 06:26

    An alternative way is to use DateTime.DaysInMonth to get the number of days in the current month as suggested by @Jade

    Since we know the first day of the month will always 1 we can use it as default for the first day with the current Month & year as current.year,current.Month,1.

    var now = DateTime.Now; // get the current DateTime 
    
    //Get the number of days in the current month
    int daysInMonth = DateTime.DaysInMonth (now.Year, now.Month); 
        
    //First day of the month is always 1
    var firstDay = new DateTime(now.Year,now.Month,1); 
        
    //Last day will be similar to the number of days calculated above
    var lastDay = new DateTime(now.Year,now.Month,daysInMonth);
    
    //So
    rdpStartDate.SelectedDate = firstDay;
    rdpEndDate.SelectedDate = lastDay; 
    

提交回复
热议问题