Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AddTicks does not cause difference to DateTime

Tags:

c#

I have following code for AddTicks method. Ticks property of datetime object is returning same value before and after the AddTick method. Why is it behaving so?

There are 10,000 ticks in a millisecond.

Ticks: The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue.

AddTicks : Adds the specified number of ticks to the value of this instance.

Note: I am using .Net 4.0 framework

CODE

    static void Main()
    {


        DateTime dt2 = new DateTime(2010, 5, 7, 10, 11, 12, 222);

        long x = dt2.Ticks;
        dt2.AddTicks(9999);

        long y = dt2.Ticks;

        bool isSame = false;
        if (x == y)
        {
            isSame = true;  
        }


        Console.WriteLine(isSame);
        System.Console.ReadKey();
    }
like image 395
LCJ Avatar asked Jan 10 '13 08:01

LCJ


People also ask

What is AddTicks?

AddTicks() method in C# is used to add a specified number of ticks to the value of this instance. It returns a new DateTime.

What is AddTicks in C#?

AddTicks() Method in C# This method is used to returns a new DateTime that adds the specified number of ticks to the value of this instance. This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation.

What is ticks DateTime?

If the DateTime object has its Kind property set to Unspecified , its ticks represent the time elapsed time since 12:00:00 midnight, January 1, 0001 in the unknown time zone. In general, the ticks represent the time according to the time zone specified by the Kind property.


1 Answers

AddTicks (and the other Add* methods) does not alter the DateTime, but returns a new object.

So you should use

dt2 = dt2.AddTicks(...)

DateTime is a value type and is immutable.

like image 121
faester Avatar answered Oct 09 '22 11:10

faester