Negative values in C# DateTime
Is there a way to set negative values when calling the DateTime constructor.
like this:
DateTime date = new DateTime(2011, 2, -1);
开发者_开发技巧
would be the same as:
DateTime date = new DateTime(2011, 1, 31);
I know this works in other languages, but the problem is that C# .net throws an exception when i'm doing this. Any ideas on how to do this in C# .net?
Use
DateTime date = new DateTime(2011, 2,1).AddDays(-1);
You can't. If you want to get the last day of the month, you should either start off with the start of the next month and then take off one day, or use DateTime.DaysInMonth(year, month)
.
Personally I'd use the second approach, as otherwise you have to make sure you handle finding the last day in December correctly by starting off with January 1st of the next year, for example. Here's the code I'd use:
DateTime date = new DateTime(year, month, DateTime.DaysInMonth(year, month));
A DateTime
is always an absolute position in time. I think what you're searching for is a TimeSpan
, which can also be negative.
精彩评论