C# 日期时间操作

C# 日期时间操作,c#,datetime,C#,Datetime,这是我的密码: DateTime startDate = Convert.ToDateTime( orderDate ).AddMonths(-1); DateTime endDate = Convert.ToDateTime( orderDate ); orderDate是我传入的有效日期 我如何始终保证startDate是orderDate的前一个月的第一天? 如何始终保证endDate是orderDate当月的最后一天 例如: orderDate = 5/4/2012 I want s

这是我的密码:

DateTime startDate = Convert.ToDateTime( orderDate ).AddMonths(-1);
DateTime endDate = Convert.ToDateTime( orderDate );
orderDate是我传入的有效日期

我如何始终保证startDate是orderDate的前一个月的第一天? 如何始终保证endDate是orderDate当月的最后一天

例如:

orderDate = 5/4/2012

I want startDate to be 4/1/2012 (or 04/1/2012 whichever is default)
I want endDate to be 4/30/2012
我怎样才能做到这一点

origDate = startDate.AddMonths(-1);
DateTime myDate = new DateTime(origDate.Year, origDate.Month, 1);

像这样的。。。我们经常这样做,以至于我们刚刚在date上创建了一个扩展方法

DateTime startDate = new DateTime( orderDate.Month == 1 ? orderDate.Year - 1 : orderDate.Year, orderDate.Month - 1, 1);
DateTime endDate = new DateTime(orderDate.Year, orderDate.Month, DateTime.DaysInMonth(orderDate.Year, OrderDate.Month));



像这样的。。。我们经常这样做,只是在date上创建了一个扩展方法。

使用DateTime构造函数,它为每年、月、日等分别获取值,。。。并相应地调整它们(即,月的第一天意味着天=1)。

使用DateTime构造函数,它为每年、月、日……分别取不同的值,。。。并相应地调整它们(即,月初意味着天=1)。

为什么要将日期时间转换为日期时间?可能重复@TimeSchmelter,因为orderDate是从两个参数传入的字符串,可以通过文本框或查询字符串进行更改。@JamesWilson:我刚才问是因为你这么说的“orderDate是我传入的有效日期“还有一个真正需要DateTime的参数。没有2012年4月31日:)可能的重复,为什么要将DateTime转换为DateTime?@TimeSchmelter,因为orderDate是从两个参数传入的字符串,可以通过文本框或查询字符串进行更改。@JamesWilson:我刚才问是因为你这么说的“orderDate是我传入的有效日期“这确实需要一个约会时间。没有2012年4月31日:)-1如果你的约会是在一月份呢?你会有错误的一年。如果答案正确,我将删除下一票。我删除了下一票,但我认为这里不需要条件运算符。不,我的意思是有几种方法可以做到这一点。我想把它塞进一行lol-1,如果你的约会是在一月份呢?你会有错误的一年。如果答案正确,我将删除下一票。我删除了下一票,但我认为这里不需要条件运算符。不,我的意思是有几种方法可以做到这一点。我试着把它塞进一行,我要用这个方法。这个问题有没有可能在12月或1月像这个问题的另一个答案一样被打破?“我只是想尽我所能涵盖所有的基础知识。@詹姆斯·威尔逊-就像你编写的任何代码一样,因此没有任何保证:)除非它被烘焙到你的ASP.NET项目中,否则你应该为它编写单元测试。在任何情况下,你都应该测试尽可能多的边缘案例(日期在2000年1月、12月等),我采用这种方法。这个问题有没有可能在12月或1月像这个问题的另一个答案一样被打破?“我只是想尽我所能涵盖所有的基础知识。@詹姆斯·威尔逊-就像你编写的任何代码一样,因此没有任何保证:)除非它被烘焙到你的ASP.NET项目中,否则你应该为它编写单元测试。在任何情况下,你都应该测试尽可能多的附带案例(日期为2000年1月、12月等)
DateTime startDate = new DateTime( orderDate.Month == 1 ? orderDate.Year - 1 : orderDate.Year, orderDate.Month - 1, 1);
DateTime endDate = new DateTime(orderDate.Year, orderDate.Month, DateTime.DaysInMonth(orderDate.Year, OrderDate.Month));
var orderDate = DateTime.Now.Date;
var endDate = orderDate.AddDays(-orderDate.Day);
var startDate  = endDate.AddDays(-(endDate.Day - 1));