Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does DateTime.Now.Ticks exactly work?

Tags:

c#

.net

datetime

People also ask

How many seconds is a DateTime tick?

A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond (see TicksPerMillisecond) and 10 million ticks in a second.

How accurate is DateTime now?

Now has an approximate resolution of 10 milliseconds on all NT operating systems. The actual precision is hardware dependent.

Is DateTime now ticks always unique?

This uses the DateTime. Now. Ticks property, which is “the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001”. It will therefore always be unique, unless the id is generated in a threaded scenario.

What are ticks time?

The smallest unit of time is the tick, which is equal to 100 nanoseconds or one ten-millionth of a second.


The resolution of DateTime.Now depends on your system timer (~10ms on a current Windows OS)...so it's giving the same ending value there (it doesn't count any more finite than that).


Not really an answer to your question as asked, but thought I'd chip in about your general objective.

There already is a method to generate random file names in .NET.

See System.Path.GetTempFileName and GetRandomFileName.

Alternatively, it is a common practice to use a GUID to name random files.


You can get the milliseconds since 1/1/1970 using such code:

private static DateTime JanFirst1970 = new DateTime(1970, 1, 1);
public static long getTime()
{
    return (long)((DateTime.Now.ToUniversalTime() - JanFirst1970).TotalMilliseconds + 0.5);
}

to convert the current datetime to file name to save files you can use

DateTime.Now.ToFileTime();

this should resolve your objective


I had a similar problem.

I would also look at this answer: Is there a high resolution (microsecond, nanosecond) DateTime object available for the CLR?.

About half-way down is an answer by "Robert P" with some extension functions I found useful.