user979033
user979033

Reputation: 6480

How to add Microsecond and Nanoseconds to DatetTime?

I want to add microseconds and nanoseconds to a DateTime.

DateTime dateTime = DateTime.Now;

for(int i = 0; i < 100000; i++)
{
    dateTime  = dateTime.AddMilliseconds(0.1);
    Console.WriteLine(dateTime.ToString("yyyy.MM.dd,HH:mm:ss.ffffff"));          
}

I can't see any difference in my dateTime. Is this the right way to do that?

Upvotes: 6

Views: 4939

Answers (1)

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98848

From DateTime.AddMilliseconds documentation;

Parameters

value

Type: System.Double

A number of whole and fractional milliseconds. The value parameter can be negative or positive. Note that this value is rounded to the nearest integer.

and also you can see it's reference source as:

public DateTime AddMilliseconds(double value)
{
    return Add(value, 1);
}

and called this Add method reference;

private DateTime Add(double value, int scale)
{
    long millis = (long)(value * scale + (value >= 0? 0.5: -0.5));
    ...
    ...
}

for value = 0.1 and scale = 1, it will be

long millis = (long)(0.6);

and this (long)(0.6) returns 0 because Explicit Numeric Conversions Table says;

When you convert from a double or float value to an integral type, the value is truncated

So, actually, you are not adding anything to that DateTime instance and you get the same results for all iterations. I would work with integers when you deal with AddXXX methods of the DateTime to preventing getting confuse.

Since 1 millisecond is 10000 tics, what you do is mathematically equal to;

DateTime dateTime = DateTime.Now;

for(int i = 0; i < 100000; i++)
{
    dateTime  = dateTime.AddTicks(1000);
    Console.WriteLine(dateTime.ToString("yyyy.MM.dd,HH:mm:ss.ffffff"));          
}

Upvotes: 7

Related Questions