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.
DateTime is an immutable type, so you can't change it.
However, you can create a new DateTime instance based on your previous instance. In your case, it sounds like you need the Date property, and you can then add a TimeSpan that represents the time of day.
int year = 2012;
int month = 12;
int day = 24;
int hour = 0;
int min = 0;
int second = 23;
DateTime dt = new DateTime(year, month, day, hour, min, second);
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:
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 theDateTime
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 atz
database entry.Adding .Date to your date sets it to midnight (00:00).
Note The equivavalent SQL is
CONVERT(DATETIME, CONVERT(DATE, @MyDate))
What makes this method so good is that it's both quick to type and easy to read. A bonus is that there is no conversion from strings.
I.e. To set today's date to 23:30, use:
You can of course replace DateTime.Now or MyDate with any date of your choice.
DateTime is an immutable type, so you can't change it.
However, you can create a new DateTime instance based on your previous instance. In your case, it sounds like you need the Date property, and you can then add a TimeSpan that represents the time of day.
Something like this:
In this way you preserve your date, while inserting a new hours, minutes and seconds part to your liking.
one liner
would bring back todays date with a time of 4:30:00, replace DateTime.Now with any date object