如果当月是12月,如何找到下个月的第一天
我正在使用以下查询来获取下个月。
int theMonth = ((System.DateTime)periodStartDate).Month+1;
但是如果periodstartDate month id = s 12月,则上述语句会抛出错误。
我想你可以用这种方式得到它
DateTime dt = new DateTime(2011,12,2); DateTime dayone = new DateTime(dt.AddMonths(1).Year, dt.AddMonths(1).Month, 1);
现在你有一个正确的DateTime
对象到下个月的第一个,随便用它做
表达式((System.DateTime)periodStartDate).Month+1
如果月份是12月则不会抛出错误 – 它只返回13.我怀疑你这样做:
var nextMonth = new DateTime(periodStartDate.Year, periodStartDate.Month + 1, 1);
这会引发错误。
试试这个:
var nextMonth = new DateTime(periodStartDate.Year, periodStartDate.Month, 1) .AddMonths(1);
我喜欢V4V的答案,但我这样写:
DateTime dt = new DateTime(2011,12,2); DateTime firstDayNextMonth = dt.AddMonths(1).AddDays(-dt.Day+1);
例如,我可能正在计算未来的时间,而这段代码可以在不剥离时间部分的情况下完成。
每个hvd最精明的评论,这段代码应该是:
DateTime dt = new DateTime(2011,12,2); DateTime firstDayNextMonth = dt.AddDays(-dt.Day+1).AddMonths(1);
int theMonth = ((System.DateTime)periodStartDate).AddMonths(1).Month;
计算theMonth
,检查它是否等于13(12月后的月份)并将值替换为1:
theMonth = theMonth==13 ? 1 : theMonth;
如果您调用AddMonths(1)
则.NET将自动将日期滚动到下一年。
periodStartDate.AddMonths(1).Month;
DateTime now = DateTime.Now; DateTime nextMonth; if(now.Day > 1) nextMonth = now.AddDays(-(now.Day - 1)).AddMonths(1); else nextMonth = now.AddMonths(1);
现在是您要开始的日期,您可以使用TheStartPeriod替换
DateTime date = DateTime.Now; Console.WriteLine(date); // Sunday 28.06.2015 г. 10:22:41 ч. int monthsBack = -1; int whichDay = 1; // It means -> what day the first day of the previous month is. DayOfWeek FirstDayOfWeek = date.AddMonths(monthsBack).AddDays(whichDay).DayOfWeek; Console.WriteLine(FirstDayOfWeek); // Friday int delta = DayOfWeek.Monday - date.AddMonths(monthsBack).AddDays(whichDay).DayOfWeek; Console.WriteLine(delta); // -4 //-4 ->Monday , -3 ->Tuesday, -2 ->Wednesday , -1 ->Thursday, 0 ->Friday
技巧部分是了解开始日期无法在当月的第一天开始,因此普通的AddMonth
可能会导致不需要的日期。 在第01天构建一个新的DateTime,然后添加月份。
var firstDayNextMonth = new DateTime(startDate.Year, startDate.Month, 1).AddMonths(+1);
顺便说一下, AddMonths
方法文档说明:
AddMonths方法计算得到的月份和年份,考虑闰年和一个月中的天数,然后调整生成的DateTime对象的日期部分。 如果结果日期不是结果月份中的有效日期,则使用结果月份的最后一个有效日期。 例如,3月31日+ 1个月= 4月30日,3月31日 – 1个月= 2月28日为非闰年,2月29日为闰年。