How can I change only the time in my DateTime
variable "s"?
DateTime s = some datetime;
Yes, just do date = datetime. strptime('26 Sep 2012', '%d %b %Y'). replace(hour=11, minute=59) .
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.
Alright I'm diving in with my suggestion, an extension method:
public static DateTime ChangeTime(this DateTime dateTime, int hours, int minutes, int seconds, int milliseconds) { return new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, hours, minutes, seconds, milliseconds, dateTime.Kind); }
Then call:
DateTime myDate = DateTime.Now.ChangeTime(10,10,10,0);
It's important to note that this extension returns a new date object, so you can't do this:
DateTime myDate = DateTime.Now; myDate.ChangeTime(10,10,10,0);
But you can do this:
DateTime myDate = DateTime.Now; myDate = myDate.ChangeTime(10,10,10,0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With