简体   繁体   中英

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?

使用

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM