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

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

问题描述

如何精确地构建实际时间的时间戳?

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

我需要像16.4.2013 9:48:00:123这样的东西。这可能吗?我有一个应用程序,其中每秒采样值10次,我需要在图形中显示。

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 a time stamp of actual time with milliseconds precision?

我怀疑你的意思是毫秒准确性 DateTime 具有很高的精度,但在精度方面相当粗糙。一般来说,你不能。通常系统时钟(其中 DateTime.Now 从其获取数据)具有大约10-15 ms的分辨率。请参阅Eric Lippert的博客文章关于精确度和准确性更多细节。

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-15 ms. See Eric Lippert's blog post about precision and accuracy for more details.

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

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

然而,不清楚,这里真的需要毫秒的准确性。如果您不关心精确时间 - 您只需要以正确的顺序显示样本,相当不错的精度,那么系统时钟应该很好。尽管如此,我建议您使用 DateTime.UtcNow 而不是 DateTime.Now ,以避免白天出现时区问题保存转换等。

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.

如果您的问题实际上只是转换 DateTime 到一个毫秒精度的字符串,我建议使用:

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

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

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