You can't change a DateTime value - it's immutable. However, you can change the variable to have a new value. The easiest way of doing that to change just the time is to create a TimeSpan with the relevant time, and use the DateTime.Date property:
DateTime s = ...;
TimeSpan ts = new TimeSpan(10, 30, 0);
s = s.Date + ts;
s
will now be the same date, but at 10.30am.
Note that DateTime
disregards daylight saving time transitions, representing "naive" Gregorian time in both directions (see Remarks section in the DateTime
docs). The only exceptions are .Now
and .Today
: they retrieve current system time which reflects these events as they occur.
This is the kind of thing which motivated me to start the Noda Time project, which is now production-ready. Its ZonedDateTime
type is made "aware" by linking it to a tz
database entry.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…