[英]How does DateTime.Now.Ticks exactly work?
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:
为了确保独特的命名,我尝试使用自1970年1月1日以来的纳秒时间:
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?
我的意思是为什么最后4个数字总是一样的? I can use this as a filename, that is not the problem, but I'm just wondering about it.
我可以使用它作为文件名,这不是问题,但我只是想知道它。
634292263478068039
634292263512888039
634292263541368039
634292263603448039
634292263680078039
DateTime.Now
的分辨率取决于你的系统计时器(在当前的Windows操作系统上大约10毫秒)......所以它在那里给出了相同的结束值(它不再计算有限值)。
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. 已经有一种在.NET中生成随机文件名的方法。
See System.Path.GetTempFileName and GetRandomFileName . 请参见System.Path.GetTempFileName和GetRandomFileName 。
Alternatively, it is a common practice to use a GUID to name random files. 或者,通常的做法是使用GUID命名随机文件。
You can get the milliseconds since 1/1/1970 using such code: 你可以使用这样的代码获得自1970年1月1日以来的毫秒数:
private static DateTime JanFirst1970 = new DateTime(1970, 1, 1);
public static long getTime()
{
return (long)((DateTime.Now.ToUniversalTime() - JanFirst1970).TotalMilliseconds + 0.5);
}
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? 我也会看看这个答案: CLR有高分辨率(微秒,纳秒)的DateTime对象吗? .
。
About half-way down is an answer by "Robert P" with some extension functions I found useful. 大约一半是“罗伯特P” 的回答 ,我发现一些有用的扩展功能。
to convert the current datetime to file name to save files you can use 将当前日期时间转换为文件名以保存可以使用的文件
DateTime.Now.ToFileTime();
this should resolve your objective 这应该解决你的目标
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.