C#日期时间与微秒正确的格式

时间:2019-03-26 08:35:26

标签: c# datetime

我的日期以微秒为单位,它是通过添加2000.1.1的滴答声来计算的,基本上可以正常工作,看起来像这样:

ulong timestampInTicks = ExtendedTimestamp * TimeSpan.TicksPerMillisecond / 10;
var startDate = new DateTime(2000, 1, 1, 0, 0, 0);
string dateWithMicroseconds =  startDate.AddTicks((long)timestampInTicks).ToString("HH:mm:ss.ffffff");

问题是返回格式,它返回给我类似19:34:34:260100的信息,所以当我尝试HH:mm:ss.fff:fff时,毫秒和微秒相结合,我得到的是19:34:34:260: 260所以毫秒翻了一番。除了使用分割字符串,还有其他方法吗?

2 个答案:

答案 0 :(得分:0)

因为微秒是毫秒/ 1000,所以参考该日期格式将返回01.01.2008 00:30:45.125.125000。毫秒:125,微秒:125000

DateTime dates =  new DateTime(2000, 1, 1, 0, 30, 45, 125);
Console.WriteLine("Date with micro and milliseconds: {0:MM/dd/yyy HH:mm:ss.fff.ffffff}",dates);

答案 1 :(得分:0)

我能想到的最简单的自定义实现。

ulong ExtendedTimestamp = 99;
ulong timeStampInTicks = ExtendedTimestamp * TimeSpan.TicksPerMillisecond / 10;
var startDate = DateTime.Now;
string dateWithMicroseconds = startDate.AddTicks((long)timeStampInTicks).ToString("HH:mm:ss.ffffff");
string dateHHmmss = dateWithMicroseconds.Split('.')[0];
string timeffffff = dateWithMicroseconds.Split('.')[1];
int precision = 3;
string milliSecs = timeffffff.Substring(0, precision);
string microSecs = timeffffff.Substring(precision, timeffffff.Length - precision);

string customFormat = string.Format("{0}:{1}:{2}", dateHHmmss, milliSecs, microSecs);