80

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?

Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148
Vaibhav Jain
  • 33,887
  • 46
  • 110
  • 163

5 Answers5

147

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);
Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
  • 3
    This method can easily result on a "System.ArgumentOutOfRangeException: Year, Month, and Day parameters describe an un-representable DateTime" when the day exists in the original year but not in the updated one. Simplest case being leap years. I would suggest something like: ` var newYear = 2017; var oldDate = new DateTime(2016, 2, 29); var newDate = oldDate.AddYears(newYear - oldD.Year); ` Notice newDate won't be 2017-2-29, which doesn't exist, but 2017-2-28 instead. – Yosoyadri Jan 01 '17 at 20:24
  • 6
    What are you talking about? There is no issue with this code. – Yusha May 01 '18 at 19:00
28

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);
Nathan Koop
  • 24,803
  • 25
  • 90
  • 125
Daniel Perez
  • 4,292
  • 4
  • 29
  • 54
17
date = new DateTime(date.year, date.month, date.day, HH, MM, SS);
Rhapsody
  • 6,017
  • 2
  • 31
  • 49
16

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.

David
  • 72,686
  • 18
  • 132
  • 173
2

It isn't possible as DateTime is immutable. The same discussion is available here: How to change time in datetime?

Community
  • 1
  • 1
cspolton
  • 4,495
  • 4
  • 26
  • 34