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

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


当前回答

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

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

其他回答

DateTime.Now.ToString(“ddMMyyyyhhmmssffff”)

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

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

我正在寻找一个类似的解决方案,基于这个线程上的建议,我使用以下方法 DateTime.Now。ToString(“MM / dd / yyyy hh: MM: ss.fff”) ,它就像魅力一样。注意:.fff是您希望捕获的精度数字。

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

DateTime.Now.Millisecond

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

另一个选择是从源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);

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