I have a DateTime variable:
DateTime date = DateTime.Now;
I want to change the time part of a DateTime variable. But when I tried to access time part (hh:mm:ss) these fields are readonly.
Can't I set these properties?
There are two ways to initialize the DateTime variable: DateTime DT = new DateTime();// this will initialze variable with a date(01/01/0001) and time(00:00:00). DateTime DT = new DateTime(2019,05,09,9,15,0);// this will initialize variable with a specific date(09/05/2019) and time(9:15:00).
Use the constructor that allows you to specify the year, month, day, hours, minutes, and seconds:
var dateNow = DateTime.Now; var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 4, 5, 6);
you can't change the DateTime object, it's immutable. However, you can set it to a new value, for example:
var newDate = oldDate.Date + new TimeSpan(11, 30, 55);
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