views:

278

answers:

4

Hi, I am trying to construct a DateTime in C# one step at a time, as in, the whole date not being in the constructor. I'm not understanding what is wrong though.

DateTime d = new DateTime((long)0);
d.AddYears(2000);

with that d.Years will still be equal to 1 though. Also, I must store the date as a long. So I can't just build the date with a huge constructor and I also can't have a persisting DateTime instance, so I dump it to a long and then restore it and I start with a value of 0. Am I suppose to start with a different value than zero?

what exactly is wrong?

+16  A: 

A DateTime structure is immutable, meaning that its properties cannot change.

The AddYears method returns a new DateTime that you must use:

DateTime d = new DateTime((long)0);
d = d.AddYears(2000);
Pierre-Alain Vigeant
+1 for immutable explanation.
Lucas B
+1  A: 

There are 12 different overloads for the DateTime constructor. There should be at least one you can adapt for your use.

This:

DateTime d = new DateTime(2000,0,0);

is better than:

DateTime d = new DateTime((long)0);
d = d.AddYears(2000);

Just construct as much of the date as you can up front and put in zeros for the other parameters.

Joel Coehoorn
I do not know the entire datetime when it is constructed, so that would fail. (it is constructed across page updates)
Earlz
You missed the point: you use as much as you do know at the time and put in zeros everywhere else.
Joel Coehoorn
+2  A: 

Probably off-topic, but if you need to persist your DateTime as a long then why not persist the value returned by its Ticks property.

You can then restore your DateTime instance by using the constructor that takes a ticks parameter:

// stage 1
DateTime dt = DateTime.MinValue.AddYears(2009);
PersistTicksToSomewhere(dt.Ticks);

// stage 2
long ticks = GetPersistedTicksFromSomewhere();
DateTime dt = new DateTime(ticks).AddMonths(8);
PersistTicksToSomewhere(dt.Ticks);

// stage 3
long ticks = GetPersistedTicksFromSomewhere();
DateTime dt = new DateTime(ticks).AddDays(20);
PersistTicksToSomewhere(dt.Ticks);

// etc etc
LukeH
You might also want to consider using the `ToBinary` and `FromBinary` methods instead of ticks if preserving the `DateTimeKind` is important.
LukeH
A: 

DateTime is immutable so you must change it as so DateTime d = new DateTime(); d d.AddYears(2000);

However this will instantiate a new DateTime 99.9% of the time this is fine but if it's nested in a loop that runs forever you're better off using one of the many DateTime constructors. Use the same rule of thumb as string and StringBuilder.

RHicke