System.FormatException:字符串 '2021-03-13 11:22:54.3100000' 未被识别为有效的日期时间

问题描述 投票:0回答:1

下面是抛出错误的行:

DateTime.ParseExact(x.FirstOrDefault(y => y.dte == "Date")?.Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)
          

我可以知道我要去哪里错了吗。

c# datetime-format
1个回答
1
投票

如果你有 optional 几分之一秒,试试 capital

F
而不是
f
;所以对于格式字符串

"yyyy-MM-dd HH:mm:ss.FFFFFFF"

你会得到

string[] tests = {
  "2021-03-13 11:22:54.3100000",
  "2021-03-13 11:22:54"
};

var results = string.Join(Environment.NewLine, tests.Select(test =>
  $"{DateTime.ParseExact(test, "yyyy-MM-dd HH:mm:ss.FFFFFFF", null):d MMMM yyyy : HH.mm.ss.ff}"));

Console.Write(results);

输出:

13 March 2021 : 11.22.54.31
13 March 2021 : 11.22.54.00

编辑: 如果你有 several 不同的格式,只需将它们作为数组传递:

string text = "2023-03-23 11:03:10";

var result = DateTime.ParseExact(text, 
  new string[] { //TODO: Put all the formats here
    "yyyy-MM-dd HH:mm:ss.FFFFFFF",
    "yyyy.MM.dd HH:mm:ss.FFFFFFF",
  }, 
  null, 
  DateTimeStyles.AssumeLocal);

系统将按照您放置的顺序尝试格式,直到找到合适的格式,或者如果没有格式符合

text
.

© www.soinside.com 2019 - 2024. All rights reserved.