Notice how we have to "save" the result from each method call to the myDateTime variable. This is because the DateTime is immutable, and its methods simply create new instances with the extra hours/minutes/seconds added.
If you need to add both hours and minutes (and/or seconds) and the same time, you can simplify the code by adding a TimeSpan to the original DateTime instead:
var myDateTime = new DateTime(2000, 01, 01); // 2000-01-01 00:00:00
myDateTime += new TimeSpan(13, 37, 42); // 2000-01-01 13:37:42
If you want to set absolute hours/minues/seconds, rather than adding to the existing values, you can use the aforementioned DateTime constructor, and reuse values for year/month/day from earlier:
In fact, you can't change the time once it's created. But you can create it easily with many constructors: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.-ctor?view=netframework-4.7.2
For example, if you want to create a DateTime changing Seconds, you can just do this:
If you have a DateTime like 2014/02/05 18:19:51 and want just 2014/02/05, you can do that:
When you construct your
DateTime
object, use a constructor that allows you to specify time:If you already have a
DateTime
object and wish to change the time, uou can add minutes, hours or seconds to yourDateTime
using simple methods:Notice how we have to "save" the result from each method call to the
myDateTime
variable. This is because theDateTime
is immutable, and its methods simply create new instances with the extra hours/minutes/seconds added.If you need to add both hours and minutes (and/or seconds) and the same time, you can simplify the code by adding a
TimeSpan
to the originalDateTime
instead:If you want to set absolute hours/minues/seconds, rather than adding to the existing values, you can use the aforementioned
DateTime
constructor, and reuse values for year/month/day from earlier:The best solution is:
Use
Date.Add
and add aNew TimeSpan
with the new time you want to addyou could add +ve/-ve values in parameter.