How can I clone a DateTime object in C#?

前端 未结 3 1171
南旧
南旧 2021-02-11 12:05

How can I clone a DateTime object in C#?

3条回答
  •  走了就别回头了
    2021-02-11 12:28

    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
    

提交回复
热议问题