如何将DateTime设置为下个月的第一天?

10

如果我有var olddate = DateTime.Parse('05/13/2012');

并且我想得到var newdate = (olddate后的下个月的第一天,以此为例是06/01/2012);

我应该怎么编码?我尝试设置月份+1,但月份没有setter。


你的例子似乎不一致。请问这是要表示2012年12月5日之后的2013年1月6日吗? - Oded
@Oded 抱歉,我使用了美国日期格式,mm/dd/yyyy。 - proseidon
1
进行了编辑,以使日期对非美国人不会产生歧义。 - Oded
5个回答

23

试一试:

olddate = olddate.AddMonths(1);
DateTime newDate = new DateTime(olddate.Year, olddate.Month, 1, 
    0, 0, 0, olddate.Kind);

忍者编辑 ftw。记得要保留 DateTimeKind 属性。很多人都会忽略它,但如果你忽略了它并将你的 DateTime 传递给不支持该属性的代码,可能会发生意外情况。 - Cory Nelson

7

这不会引起任何超出范围的错误,并且将保留 DateTime 的类型。

dt = dt.AddMonths(1.0);
dt = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0, dt.Kind);

3

试试这个简单的一行代码:

var olddate = DateTime.Parse("05/13/2012");
var newdate = olddate.AddDays(-olddate.Day + 1).AddMonths(1);
// newdate == DateTime.Parse("06/01/2012")

2

您需要正确定义月份和年份,然后设置第一天。请尝试以下操作:

// define the right month and year of next month.
var tempDate = oldDate.AddMonths(1);

// define the newDate with the nextmonth and set the day as the first day :)
var newDate = new DateTime(tempDate.Year, tempDate.Month, 1); //create 

0

许多例子...选择你的毒药 ;)

var olddate = DateTime.Parse("05/12/2012");

int currentDay = ((DateTime)olddate).Day;
//can always replace the while loop and just put a 1 for current day
while(currentDay != 1)
   currentDay--;

var newdate = (DateTime.Parse(olddate.AddMonths(1).Month.ToString() + "/" + currentDay.ToString() + "/" + olddate.AddMonths(1).Year.ToString()));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接