How does DateTime.Now.Ticks exactly work?

2020-02-24 05:50发布

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# .net datetime
5条回答
虎瘦雄心在
2楼-- · 2020-02-24 06:15

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.

查看更多
放荡不羁爱自由
3楼-- · 2020-02-24 06:18

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.

查看更多
迷人小祖宗
4楼-- · 2020-02-24 06:25

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

DateTime.Now.ToFileTime();

this should resolve your objective

查看更多
够拽才男人
5楼-- · 2020-02-24 06:29

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);
}
查看更多
等我变得足够好
6楼-- · 2020-02-24 06:37

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

查看更多
登录 后发表回答