获取当月的第一天和最后一天

时间:2014-02-21 01:24:48

标签: c# date

我在这里有开始日期结束日期的2个日期选择器。

如何获得当月的第一天和最后一天

rdpStartDate.SelectedDate = DateTime.Now;
rdpEndDate.SelectedDate = DateTime.Now;

7 个答案:

答案 0 :(得分:86)

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

答案 1 :(得分:28)

var now = DateTime.Now;
var first = new DateTime(now.Year, now.Month, 1);
var last = first.AddMonths(1).AddDays(-1);

您还可以使用DateTime.DaysInMonth方法:

var last = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));

答案 2 :(得分:9)

var myDate = DateTime.Now;
var startOfMonth = new DateTime(myDate.Year, myDate.Month, 1);
var endOfMonth = startOfMonth.AddMonths(1).AddDays(-1);

这应该可以满足您的需求。

答案 3 :(得分:6)

尝试使用此代码,它已经在c#

中构建
int lastDay = DateTime.DaysInMonth (2014, 2);

,第一天总是1。

祝你好运!

答案 4 :(得分:1)

受Chris Shao的回答启发,我已经为这两个值创建了函数:

private DateTime FirstDayOfMonth()
{
    return new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
}

private DateTime LastDayOfMonth()
{
    return new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1);
}

答案 5 :(得分:0)

string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");

答案 6 :(得分:0)

另一种方法是使用DateTime.DaysInMonth来获取@Jade建议的当月的天数

由于我们知道月份的第一天将始终为1,因此我们可以将其作为第一天的默认值,将当前的月份和年份设为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;