How to set only temporary part of DateTime variable in C #

I have a DateTime variable:

DateTime date = DateTime.Now; 

I want to change the temporary part of a DateTime variable. But when I tried to access the time part (hh: mm: ss), these fields will be read only.

Can't set these properties?

+64
c # datetime
Nov 23 '10 at 2:30 p.m.
source share
5 answers

Use the constructor, which 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); 
+115
Nov 23 '10 at 14:33
source share
— -

you cannot change the DateTime object, it is immutable. However, you can set it to a new value, for example:

 var newDate = oldDate.Date + new TimeSpan(11, 30, 55); 
+18
Nov 23 '10 at 14:36
source share
 date = new DateTime(date.year, date.month, date.day, HH, MM, SS); 
+12
Nov 23 '10 at 14:33
source share

I'm not sure what you are trying to do, but you can set the date / time exactly the way you want, in several ways ...

You can specify 12/25/2010 4:58 PM using

 DateTime myDate = Convert.ToDateTime("2010-12-25 16:58:00"); 

OR, if you have an existing datetime construct, say 12/25/2010 (and any random time), and you want to set it before 12/25/2010 16:58, you can do it like this:

 DateTime myDate = ExistingTime.Date.AddHours(16).AddMinutes(58); 

ExistingTime.Date will be 12/25 at midnight, and you simply add hours and minutes to get there.

+12
Nov 23 2018-10-23
source share

This is not possible because DateTime is immutable. The same discussion is available here: How to change time in datetime?

+2
Nov 23 '10 at 14:35
source share



All Articles