C#を使用して時間をミリ秒単位で取得します
-
26-09-2019 - |
質問
私は、私は時間をミリ秒単位で取得する必要のあるプログラムを作ってるんです。時間によって、私は自分自身に決して等しく、常にそれが二前に比べ1000の数字大きい数を意味します。私はDateTime.Now
にTimeSpan
を変換し、それからTotalMilliseconds
を取得しようとしました...しかし、私はそれが完全に正確ではないと聞きました。
これを行うための簡単な方法はありますか?
解決
他のヒント
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
これは、様々なUnixの変換方法は DateTimeOffset
クラス(.NET Frameworkの4.6+、.NET標準1.3 +):
long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();
DateTime.Ticks
プロパティは、日付と時刻を表すティック数を取得します。
万マダニミリ秒(毎秒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()
。それプット完全日の変更、などを排除することが知ら参照ベースミリ秒の形式であなたの読書ます。