TimeSpan.Parse 微秒和毫秒的跨度

TimeSpan.Parse microsecond and millisecond spans

我正在使用 return 时间跨度为以下格式的 Web 服务

我希望能够准确地将这些解析为 TimeSpan 对象。目前我正在使用 TimeSpan.Parse 但这两次都失败了:

TimeSpan.Parse(json["time"].ToString());
// Exception: String was not recognized as a valid TimeSpan.

如何解析这些值?

据我所知,TimeSpan 结构不支持这样的单元解析。您必须自己检查并拆下设备。

对于毫秒,然后使用 FromMilliseconds. For microseconds either rescale the value to ms (FromMilliseconds accepts a double) or use FromTicks,其中每个刻度为 100 ns。

使用正则表达式来检测你有什么 - 微秒或毫秒。或者只是简单地检查 EndsWith

(\d*.\d*)µs // for microseconds
(\d*.\d*)ms  // for milliseconds

@Chris 已经写过 - 时间跨度不允许您解析微秒。