2011-01-24 44 views
6

有沒有方法來調用DateTime構造函數時設置負值。C#中的負值DateTime

這樣的:

DateTime date = new DateTime(2011, 2, -1); 

將是一樣的:

DateTime date = new DateTime(2011, 1, 31); 

我知道這個作品在其他語言,但問題是,C#.NET拋出,當我異常這樣做。任何想法如何在C#.net中做到這一點?

+0

這不能以不同的.net語言工作,因爲`DateTime`是公共庫的一部分。 – Andrey 2011-01-24 11:08:26

+0

爲什麼你想要一個負面的日期時間?如果你想減去時間,那麼要麼使用.AddDays(-x)或.AddMonths(-x)等,要麼有另一個叫做TimeSpan的類,你可以使用它不是1整天或者整整1個月等。 – WraithNath 2011-01-24 11:08:55

回答

8

你不能。如果你想得到這個月的最後一天,你應該從下個月開始,然後在一天內起飛,或者使用DateTime.DaysInMonth(year, month)。例如,我個人會使用第二種方法,否則您必須確保您在12月的最後一天正確處理,例如從第二年的1月1日開始。這裏是我要使用的代碼:

DateTime date = new DateTime(year, month, DateTime.DaysInMonth(year, month)); 
10

使用

DateTime date = new DateTime(2011, 2,1).AddDays(-1); 
1

A DateTime總是在時間上的絕對位置。我認爲你要搜索的是TimeSpan,這也可能是負面的。