Get DateTime.Now with milliseconds precision

2019-01-10 02:57发布

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.

11条回答
仙女界的扛把子
2楼-- · 2019-01-10 03:07

try using datetime.now.ticks. this provides nanosecond precision. taking the delta of two ticks (stoptick - starttick)/10,000 is the millisecond of specified interval.

https://docs.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=netframework-4.7.2

查看更多
冷血范
3楼-- · 2019-01-10 03:09

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 .fff are the precision numbers that you wish to capture.

查看更多
放我归山
4楼-- · 2019-01-10 03:09

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

DateTime.Now.Millisecond

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

查看更多
We Are One
5楼-- · 2019-01-10 03:15

Use DateTime Structure with milliseconds and format like this:

string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", 
CultureInfo.InvariantCulture);
timestamp = timestamp.Replace("-", ".");
查看更多
别忘想泡老子
6楼-- · 2019-01-10 03:20

DateTime.Now.ToString("ddMMyyyyhhmmssffff")

查看更多
姐就是有狂的资本
7楼-- · 2019-01-10 03:21

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);
}
查看更多
登录 后发表回答