DateTime ParseExact 给出 System.FormatException:

DateTime ParseExact gives System.FormatException:

我收到以下错误:

System.FormatException: 'String '{ ActualInstallDate = 17/04/2020 09:06:23 }' was not recognised as a valid DateTime.

我必须补充一点,在数据库中 ActualInstallDate 可以为空,这就是我将其转换为字符串 'trick' 的原因。错误出现在解析 actualInstallDates 时。不知道这里出了什么问题。

非常感谢任何建议。

var actualInstallDates = _context.Units.Where(u => u.ID == unitID)
                .Select(u => new {
                    u.ActualInstallDate
                }).Single().ToString();

            if (actualInstallDates != null)
            {

                DateTime actualInstallDate = DateTime.ParseExact(actualInstallDates, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                var nowString = DateTime.Now.ToString("dd/MM/yyyy");
                DateTime now = DateTime.ParseExact(nowString, "dd/MM/yyyy", CultureInfo.InvariantCulture);

                var averageWorkOver = (Math.Ceiling(Math.Ceiling(Convert.ToDecimal(now - actualInstallDate)) / 1000 * 60 * 60 * 24) / workOverList.Count).ToString();
                ViewBag.AverageWorkOver = averageWorkOver;
            }
[Column(TypeName = "datetime2")] 
[Display(Name = "ActualInstallDate", Description = "ActualInstallDate_Description", ResourceType = typeof(Resource.Models.Unit))] 
public DateTime? ActualInstallDate { get; set; } 
  • 首先你不需要select它变成匿名对象(如果 ActualInstallDate 是数据库中的字符串):
var actualInstallDates = _context.Units
    .Where(u => u.ID == unitID)
    .Select(u => u.ActualInstallDate)
    .SingleOrDefault();
if (actualInstallDates != null)
{...}

如果您仍然想要,请不要在上面调用 ToString

var actualInstallDates = _context.Units.Where(u => u.ID == unitID)
    .Select(u => new { u.ActualInstallDate })
    .Single();
if (actualInstallDates.ActualInstallDate != null)
{
    DateTime.ParseExact(actualInstallDates.ActualInstallDate ...)
    ...
}
  • 其次你的日期格式与字符串不匹配,尝试使用
DateTime.ParseExact(actualInstallDates, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture)

UPD

因为你的字段是 DateTime? 看来你在 Nullable<> 结构上丢失了 Value 属性 所以你只需要从数据库中获取你的日期和使用 actualInstallDates.Value:

var actualInstallDates = _context.Units
    .Where(u => u.ID == unitID)
    .Select(u => u.ActualInstallDate)
    .Single()

if (actualInstallDates != null)
{
    var averageWorkOver = (Math.Ceiling(Math.Ceiling(Convert.ToDecimal(DateTime.Now - actualInstallDates.Value)) / 1000 * 60 * 60 * 24) / workOverList.Count).ToString();
   ViewBag.AverageWorkOver = averageWorkOver;
}



您没有在格式字符串中指定时间。您可以从日期字符串中截断时间部分,也可以将时间添加到格式字符串中。 像这样:

 DateTime actualInstallDate = DateTime.ParseExact(actualInstallDates, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);