以毫秒precision获取DateTime.Now [英] Get DateTime.Now with milliseconds precision

查看:147
本文介绍了以毫秒precision获取DateTime.Now的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能准确地构建实际时间毫秒precision时间戳?

我需要像2013年4月16日9:48:00:123。这可能吗?我有一个应用程序,我在那里采样值每秒10次,我需要向他们展示一个图表。


解决方案

  我

如何能准确地构造的实际时间的时标以毫秒precision?


我怀疑你的意思是毫秒级的精度的。 的DateTime 有很多precision的,但在精度方面相当粗糙。一般来说,你不能。通常系统时钟(这是 DateTime.Now 从获取数据)有大约10-15ms的分辨率。见埃里克利珀的<一个href=\"http://blogs.msdn.com/b/ericlippert/archive/2010/04/08/$p$pcision-and-accuracy-of-datetime.aspx\">blog发布关于precision和准确性的更多细节。

如果你需要比这更准确的计时,你可能要考虑使用NTP客户端。

不过,目前还不清楚,你真的需要在这里毫秒精度。如果你不关心的确切的时间 - 你只是想展示样品按正确的顺序,以pretty好的精度,则系统时钟应该罚款。我建议你​​使用 DateTime.UtcNow ,而不是 DateTime.Now 不过,要避免日光左右时区问题节省转换等。

如果你的问题是的实际的只是围绕一个转换的DateTime 来毫秒precision一个字符串,我建议使用:

 字符串时间戳= DateTime.UtcNow.ToString(YYYY-MM-DD HH:MM:SS.FFF
                                            CultureInfo.InvariantCulture);

(注意,不像你的样品,这是排序,并不太可能导致它周围是否的意思是月/日/年或日/月/年的困惑。)

How can I exactly construct a time stamp of actual time with milliseconds precision?

I need something like 16.4.2013 9:48:00:123. Is this possible? I have an application, where I sample values 10 times per second, and I need to show them in a graph.

解决方案

how can I exactly construct time stamp of actual time with milliseconds precision?

I suspect you mean millisecond accuracy. DateTime has a lot of precision, but is fairly coarse in terms of accuracy. Generally speaking, you can't. Usually the system clock (which is where DateTime.Now gets its data from) has a resolution of around 10-15ms. See Eric Lippert's blog post about precision and accuracy for more details.

If you need more accurate timing than this, you may want to look into using an NTP client.

However, it's not clear that you really need millisecond accuracy here. If you don't care about the exact timing - you just want to show the samples in the right order, with "pretty good" accuracy, then the system clock should be fine. I'd advise you to use DateTime.UtcNow rather than DateTime.Now though, to avoid time zone issues around daylight saving transitions etc.

If your question is actually just around converting a DateTime to a string with millisecond precision, I'd suggest using:

string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
                                            CultureInfo.InvariantCulture);

(Note that unlike your sample, this is sortable and less likely to cause confusion around whether it's meant to be "month/day/year" or "day/month/year".)

这篇关于以毫秒precision获取DateTime.Now的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆