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

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


当前回答

另一个选择是从源DateTime值构造一个新的DateTime实例:

// current date and time
var now = DateTime.Now;

// modified date and time with millisecond accuracy
var msec = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Millisecond, now.Kind);

不需要做任何到字符串和从字符串的转换,而且它的代码也非常容易理解和可读性强。

其他回答

这应该可以工作:

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

如果你不需要显示它,只需要知道时间差,那就不要把它转换成字符串。将其保留为DateTime.Now();

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

例子

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'));

尝试使用datetime.now.ticks。这提供了纳秒精度。取两个滴答(停止滴答-开始滴答)/10,000的增量为指定间隔的毫秒。

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

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

DateTime.Now.Millisecond

但如果你要比较日期,TimeSpan是最好的选择。

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

如果你想要微秒,只需将10000改为10,如果你想要微秒的10,则删除/ 10000。

另一个选择是从源DateTime值构造一个新的DateTime实例:

// current date and time
var now = DateTime.Now;

// modified date and time with millisecond accuracy
var msec = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Millisecond, now.Kind);

不需要做任何到字符串和从字符串的转换,而且它的代码也非常容易理解和可读性强。