如何将长毫秒(纳秒)部分的字符串解析为 DateTime?

How to parse string with long milliseconds (nanoseconds) part to DateTime?

我正在尝试找出以下给定日期时间文字的正确字符串格式:

18-JUN-13 12.17.36.000000000

使用MSDN,我设法组成了以下格式:

"d'-'MMM'-'y'T'h'.'m'.'s'.'fff"

但是当使用 DateTime.ParseExact 时,解析失败并显示 FormatExceptionString 未被识别为有效的 DateTime

我的代码:

DateTime.ParseExact("18-JUN-13 12.17.36.000000000", "d'-'MMM'-'y'T'h'.'m'.'s'.'fff", null);

您可以使用

dd-MMM-yy hh.mm.ss.fffffff

基于英语 的文化,例如 InvariantCulture。我现在在手机上,所以我不能试试:(

AFAIK,毫秒部分解析限制是 7,这就是为什么你不能解析你的字符串 而不 操纵它.你可以像这样使用它;

var dt = DateTime.ParseExact("18-JUN-13 12.17.36.0000000",
                             "dd-MMM-yy HH.mm.ss.fffffff",
                             CultureInfo.InvariantCulture);

看起来这就是为什么我们可能将 The "fffffff" custom format 作为毫秒的顶部字符。来自文档;

Although it is possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.

你问了;

How would you have manipulate the string?

好吧,一种获取逗号的最后一个索引并将其子串到 8 索引之后的方法;

string s = "18-JUN-13 12.17.36.000000000";
var dateString = s.Substring(0, s.LastIndexOf(".") + 8);

你有一堆格式不正确的单引号。试试这个

DateTime.ParseExact("18-JUN-13 12.17.36.000000000", "d-MMM-yTh.m.s.fff", null);