简体   繁体   English

C#DateTime中的负值

[英]Negative values in C# DateTime

Is there a way to set negative values when calling the DateTime constructor. 有没有一种方法可以在调用DateTime构造函数时设置负值。

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. 我知道这可以在其他语言中使用,但是问题是C#.net在执行此操作时会引发异常。 Any ideas on how to do this in C# .net? 关于如何在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) . 如果要获取月份的最后一天,则应该从下个月的月初开始,然后再起飞一天,或者使用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. 就我个人而言,我将使用第二种方法,因为例如,您必须确保从第二年的1月1日开始正确地找到12月的最后一天。 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. DateTime始终是时间中的绝对位置。 I think what you're searching for is a TimeSpan , which can also be negative. 我认为您要搜索的是TimeSpan ,它也可以是负数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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