How to set only time part of a DateTime variable in C# [duplicate]
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?
Solution 1:
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);
Solution 2:
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);