Why .Net DateTime properties cannot be assigned to? It would be useful to be able to do things like:
DateTime saveNow = DateTime.Now;
saveNow.Second = 0; //Error, it does not compile
Why .Net DateTime properties cannot be assigned to? It would be useful to be able to do things like:
DateTime saveNow = DateTime.Now;
saveNow.Second = 0; //Error, it does not compile
Because they are accessor properties, thus read only.
DateTime now = DateTime.Now;
DateTime saveNow
= new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
try this:
DateTime saveNow = DateTime.Now;
saveNow.AddSeconds(-savenow.Second);
AddSeconds
doesn't change the value, it returns a new instance with the new value. This version works:
saveNow = saveNow.AddSeconds(-savenow.Second);
I summarize what @SLaks and @Gabe said:
DateTime is a struct (not a class) and mutable struct are bad practice. Check here for details Why are mutable structs evil?
Because of this, DateTime is by design not mutable.
To set the DateTime 'seconds' field to 0 you can use this code:
DateTime now = DateTime.Now;
DateTime saveNow
= new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);