112

How can I clone a DateTime object in C#?

Magisch
  • 7,312
  • 9
  • 36
  • 52
Iain
  • 9,432
  • 11
  • 47
  • 64

3 Answers3

228

DateTime is a value type (struct)

This means that the following creates a copy:

DateTime toBeClonedDateTime = DateTime.Now;
DateTime cloned = toBeClonedDateTime;

You can also safely do things like:

var dateReference = new DateTime(2018, 7, 29);
for (var h = 0; h < 24; h++) {
  for (var m = 0; m < 60; m++) {
    var myDateTime = dateReference.AddHours(h).AddMinutes(m);
    Console.WriteLine("Now at " + myDateTime.ToShortDateString() + " " + myDateTime.ToShortTimeString());
  }
}

Note how in the last example myDateTime gets declared anew in each cycle; if dateReference had been affected by AddHours() or AddMinutes(), myDateTime would've wandered off really fast – but it doesn't, because dateReference stays put:

Now at 2018-07-29 0:00
Now at 2018-07-29 0:01
Now at 2018-07-29 0:02
Now at 2018-07-29 0:03
Now at 2018-07-29 0:04
Now at 2018-07-29 0:05
Now at 2018-07-29 0:06
Now at 2018-07-29 0:07
Now at 2018-07-29 0:08
Now at 2018-07-29 0:09
...
Now at 2018-07-29 23:55
Now at 2018-07-29 23:56
Now at 2018-07-29 23:57
Now at 2018-07-29 23:58
Now at 2018-07-29 23:59
Bogdan Stăncescu
  • 5,320
  • 3
  • 24
  • 25
Pieter van Ginkel
  • 29,160
  • 8
  • 71
  • 111
30
var original = new DateTime(2010, 11, 24);
var clone = original;

DateTime is a value type, so when you assign it you also clone it. That said, there's no point in cloning it because it's immutable; typically you'd only clone something if you had the intention of changing one of the copies.

Greg Beech
  • 133,383
  • 43
  • 204
  • 250
  • 2
    +1 Agreed. The way I got around the problem was to create a new DateTime object and just copy the required parts I wanted to clone such as (day, month, year) from the original datetime object and then set the time manually for the new object.... as an example. – Dalbir Singh Nov 24 '10 at 11:15
15

DateTime is a value type so everytime you assign it to a new variable you are cloning.

DateTime foo = DateTime.Now;
DateTime clone = foo;
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928