How to set only time part of a DateTime variable in C#

C#.NetDatetime

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

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);

Solution 3 - C#

date = new DateTime(date.year, date.month, date.day, HH, MM, SS);

Solution 4 - C#

I'm not sure exactly what you're trying to do but you can set the date/time to exactly what you want in a number of ways...

You can specify 12/25/2010 4:58 PM by 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 to 12/25/2010 4:58 PM, you could do so like this:

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

The ExistingTime.Date will be 12/25 at midnight, and you just add hours and minutes to get it to the time you want.

Solution 5 - C#

It isn't possible as DateTime is immutable. The same discussion is available here: https://stackoverflow.com/questions/1859248/how-to-change-time-in-datetime

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVaibhav JainView Question on Stackoverflow
Solution 1 - C#Ahmad MageedView Answer on Stackoverflow
Solution 2 - C#Daniel PerezView Answer on Stackoverflow
Solution 3 - C#RhapsodyView Answer on Stackoverflow
Solution 4 - C#DavidView Answer on Stackoverflow
Solution 5 - C#cspoltonView Answer on Stackoverflow