How does DateTime.Now.Ticks exactly work?

C#.NetDatetime

C# Problem Overview


In my application I generate files at random opportunities. To ensure a unique naming, I tried to use the nano seconds since 1.1.1970:

long time = DateTime.Now.Ticks;
String fileName = Convert.ToString(time);
Console.WriteLine(fileName);

Now I observed something weird. Why is the output like that? I mean why are the last 4 numbers always the same? I can use this as a filename, that is not the problem, but I'm just wondering about it.

634292263478068039
634292263512888039
634292263541368039
634292263603448039
634292263680078039

C# Solutions


Solution 1 - C#

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).

Solution 2 - C#

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.

Solution 3 - C#

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);
}

Solution 4 - C#

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

DateTime.Now.ToFileTime();

this should resolve your objective

Solution 5 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionanonView Question on Stackoverflow
Solution 1 - C#Nick CraverView Answer on Stackoverflow
Solution 2 - C#RB.View Answer on Stackoverflow
Solution 3 - C#Shadow Wizard Says No More WarView Answer on Stackoverflow
Solution 4 - C#SuhumarView Answer on Stackoverflow
Solution 5 - C#HeziView Answer on Stackoverflow