使用C#获取时间以毫秒计算
-
26-09-2019 - |
题
我在做节目中,我需要以毫秒为单位的时间。到时候,我的意思是一个数字,是永远不会等于本身,始终是1000号大于它是在一秒钟前。我试着转换DateTime.Now
到TimeSpan
并获得从该TotalMilliseconds
......但我听说这是不完全准确的。
有没有更简单的方式来做到这一点?
解决方案
其他提示
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
这实际上是各种Unix转换方法是如何在 DateTimeOffset
一个实施>类(.NET框架4.6+,.NET标准1.3 +):
long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();
在DateTime.Ticks
属性获取表示的日期和时间的蜱的数目。
10,000蜱是毫秒(每秒10,000,000蜱)。
您可以尝试QueryPerformanceCounter
本地方法。请参见 http://www.pinvoke.net/default.aspx/kernel32/QueryPerformanceCounter .HTML 了解详情。这是Stopwatch
类使用什么。
请参阅如何获得的刻度精确时间戳.NET / C#?获得更多的信息。
Stopwatch.GetTimestamp()
可以访问此方法:
public static long GetTimestamp() {
if(IsHighResolution) {
long timestamp = 0;
SafeNativeMethods.QueryPerformanceCounter(out timestamp);
return timestamp;
}
else {
return DateTime.UtcNow.Ticks;
}
}
我使用下面的类。我发现在互联网上一次,假设是最好的 NOW()的。
/// <summary>Class to get current timestamp with enough precision</summary>
static class CurrentMillis
{
private static readonly DateTime Jan1St1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>Get extra long current timestamp</summary>
public static long Millis { get { return (long)((DateTime.UtcNow - Jan1St1970).TotalMilliseconds); } }
}
来源未知。
我用DateTime.Now.TimeOfDay.TotalMilliseconds(当前日),希望它可以帮助你为好。
使用System.DateTime.Now.ToUniversalTime()
。这使你在一个已知的参考基础的毫秒格式读数完全消除一天的变化,等等。
不隶属于 StackOverflow