-1

I can't use following Datetime subtract method.

https://msdn.microsoft.com/ja-jp/library/system.datetime.subtract(v=vs.110).aspx

I use Microsoft Visual Studio Proffesional 2013 and VisualBasic2013 and .NetFrameWork Version 4.5.50938

I want to use above method. I can use Add method like this:

Dim dt As Datetime = Nothing
dt.Add(New TimeSpan(1))

I want to know why although there is the homepage that is Datetime. Subtract, I can't use subtract method......

Jande
  • 1,695
  • 2
  • 20
  • 32
N.Ryo
  • 25
  • 3

1 Answers1

5

Let's see what happens when you try to create a DateTime as Nothing:

Dim dt As DateTime = Nothing
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss.fffffff"))

we get "0001-01-01 00:00:00.0000000". This is the earliest datetime that can be represented by a DateTime. It can't hold a "value" of Nothing because it is a Value type: Why is null not allowed for DateTime in C#?.

Let's try adding 1 tick:

dt.Add(New TimeSpan(1))
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss.fffffff"))

Oh! We get "0001-01-01 00:00:00.0000000" again. The tick was not added on. That is because the Add method returns a new DateTime - it does not affect the one that Add was invoked on.

Let's try again:

dt = dt.Add(New TimeSpan(1))
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss.fffffff"))

Now we get "0001-01-01 00:00:00.0000001", as intended.

What happens if we try to go earlier than the first allowed DateTime?

Dim dt As DateTime = Nothing
dt = dt.Subtract(New TimeSpan(1))

It throws a System.ArgumentOutOfRangeException.

Community
  • 1
  • 1
Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • Just a heads up: some users may find the tone of this answer a bit too flippant. Personally I have little issue with it, but others seem to think differently. – deceze Nov 29 '16 at 10:29