C# 获取当前时间 DateTime类型 精确到微秒
在C#中,DateTime类型的精确度最小到毫秒级别,无法直接精确到微秒级别。但是可以通过使用Stopwatch类来获取当前时间的微秒级别精确度。
以下是一个示例代码:
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
DateTime currentTime = DateTime.Now;
long microseconds = stopwatch.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));
Console.WriteLine("当前时间: {0}.{1:D6}", currentTime.ToString("yyyy-MM-dd HH:mm:ss"), microseconds);
stopwatch.Stop();
}
}
这段代码使用了Stopwatch类来计算从程序开始运行到获取当前时间的时间间隔,然后将其转换为微秒。注意,这种方法只能提供近似的微秒级别精确度,因为Stopwatch类的精确度也受到系统时钟的限制。
原文地址: http://www.cveoy.top/t/topic/iFb9 著作权归作者所有。请勿转载和采集!