C# 以毫秒精度获取 DateTime.Now

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16032451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:46:49  来源:igfitidea点击:

Get DateTime.Now with milliseconds precision

c#datetimeprecisionmilliseconds

提问by LuckyHK

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.

我需要类似 16.4.2013 9:48:00:123 的内容。这可能吗?我有一个应用程序,我每秒对值进行 10 次采样,我需要将它们显示在图表中。

回答by Pyromancer

This should work:

这应该有效:

DateTime.Now.ToString("hh.mm.ss.ffffff");

If you don't need it to be displayed and just need to know the time difference, well don't convert it to a String. Just leave it as, DateTime.Now();

如果您不需要显示它而只需要知道时差,那么不要将其转换为字符串。就这样吧,DateTime.Now();

And use TimeSpanto know the difference between time intervals:

并用于TimeSpan了解时间间隔之间的差异:

Example

例子

DateTime start;
TimeSpan time;

start = DateTime.Now;

//Do something here

time = DateTime.Now - start;
label1.Text = String.Format("{0}.{1}", time.Seconds, time.Milliseconds.ToString().PadLeft(3, '0'));

回答by Jon Skeet

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

如何以毫秒精度准确构建实际时间的时间戳?

I suspect you mean millisecond accuracy. DateTimehas 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.Nowgets its data from) has a resolution of around 10-15 ms. See Eric Lippert's blog post about precision and accuracyfor more details.

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

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

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

However, it's not clear that you really need millisecond accuracy here. If you don't care about the exacttiming - 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.UtcNowrather than DateTime.Nowthough, to avoid time zone issues around daylight saving transitions, etc.

但是,目前尚不清楚您是否真的需要毫秒精度。如果你不关心确切的时间——你只想以正确的顺序显示样本,“非常好”的准确性,那么系统时钟应该没问题。我建议您使用DateTime.UtcNow而不是使用DateTime.Now,以避免围绕夏令时转换等的时区问题。

If your question is actuallyjust around converting a DateTimeto a string with millisecond precision, I'd suggest using:

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

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

(请注意,与您的示例不同,这是可排序的,并且不太可能导致混淆它是“月/日/年”还是“日/月/年”。)

回答by Renae

Pyromancer's answerseems pretty good to me, but maybe you wanted:

Pyromancer 的回答对我来说似乎很好,但也许你想要:

DateTime.Now.Millisecond

But if you are comparing dates, TimeSpan is the way to go.

但如果您要比较日期,TimeSpan 是最佳选择。

回答by amol jadhao

DateTime.Now.ToString("ddMMyyyyhhmmssffff")

DateTime.Now.ToString("ddMMyyyyhhmmssffff")

回答by Roland Dietz

As far as I understand the question, you can go for:

据我了解这个问题,你可以去:

DateTime dateTime = DateTime.Now;
DateTime dateTimeInMilliseconds = dateTime.AddTicks(-1 * dateTime.Ticks % 10000); 

This will cut off ticks smaller than 1 millisecond.

这将切断小于 1 毫秒的滴答声。

回答by Jozcar

I was looking for a similar solution, base on what was suggested on this thread, I use the following DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff"), and it work like charm. Note: that .fffare the precision numbers that you wish to capture.

我正在寻找一个类似的解决方案,基于这个线程上的建议,我使用了以下内容 DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff"),它的工作原理很有趣。注意:这.fff是您希望捕获的精度数字。

回答by distiking

public long millis() {
  return (long.MaxValue + DateTime.Now.ToBinary()) / 10000;
}

If you want microseconds, just change 10000to 10, and if you want the 10th of micro, delete / 10000.

如果您想要微秒,只需更改1000010,如果您想要微秒的 10,请删除/ 10000

回答by Jacman

Use DateTime Structure with milliseconds and format like this:

使用具有毫秒和格式的 DateTime 结构,如下所示:

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

回答by birch

If you still want a date instead of a string like the other answers, just add this extension method.

如果您仍然需要日期而不是像其他答案那样的字符串,只需添加此扩展方法。

public static DateTime ToMillisecondPrecision(this DateTime d) {
    return new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute,
                        d.Second, d.Millisecond, d.Kind);
}

回答by Stochastically

The trouble with DateTime.UtcNowand DateTime.Nowis that, depending on the computer and operating system, it may only be accurate to between 10 and 15 milliseconds. However, on windows computers one can use by using the low level function GetSystemTimePreciseAsFileTimeto get microsecond accuracy, see the function GetTimeStamp()below.

的麻烦DateTime.UtcNowDateTime.Now在于,根据在计算机上和操作系统,它可能只精确到毫秒10和15之间。但是,在 Windows 计算机上,可以使用低级函数GetSystemTimePreciseAsFileTime来获得微秒精度,请参阅GetTimeStamp()下面的函数。

    [System.Security.SuppressUnmanagedCodeSecurity, System.Runtime.InteropServices.DllImport("kernel32.dll")]
    static extern void GetSystemTimePreciseAsFileTime(out FileTime pFileTime);

    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
    public struct FileTime  {
        public const long FILETIME_TO_DATETIMETICKS = 504911232000000000;   // 146097 = days in 400 year Gregorian calendar cycle. 504911232000000000 = 4 * 146097 * 86400 * 1E7
        public uint TimeLow;    // least significant digits
        public uint TimeHigh;   // most sifnificant digits
        public long TimeStamp_FileTimeTicks { get { return TimeHigh * 4294967296 + TimeLow; } }     // ticks since 1-Jan-1601 (1 tick = 100 nanosecs). 4294967296 = 2^32
        public DateTime dateTime { get { return new DateTime(TimeStamp_FileTimeTicks + FILETIME_TO_DATETIMETICKS); } }
    }

    public static DateTime GetTimeStamp() { 
        FileTime ft; GetSystemTimePreciseAsFileTime(out ft);
        return ft.dateTime;
    }