You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DateTime.ParseExact报错:字符串未被识别为有效DateTime求助

Fixing "String was not recognized as a valid DateTime" with DateTime.ParseExact

Hey there, let's break down why your DateTime parsing is throwing errors and fix them step by step!

1. Problem with StartDate parsing

Your code has a small but critical mistake in the substring step:

reqDate = reqDate.Substring(0, reqDate.IndexOf(" ") + 1);

Adding +1 here includes the space character at the end of your date string, so you end up with "05/15/2018 " (note the trailing space) instead of clean "05/15/2018". When you try to parse this with the format "MM/dd/yyyy", the extra space doesn't match the format rules—hence the error.

Fix for StartDate

Option 1: Remove the +1 to exclude the trailing space:

var reqDate = Request.QueryString["StartDate"];
reqDate = reqDate.Substring(0, reqDate.IndexOf(" ")); // Now we get "05/15/2018" with no extra space
timingRequest.ReqDate = DateTime.ParseExact(reqDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);

Option 2: Even better, skip manual substring entirely. Parse the full datetime string and extract just the date part—this avoids any hidden character issues:

var reqDateStr = Request.QueryString["StartDate"];
if (DateTime.TryParseExact(reqDateStr, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime reqDate))
{
    timingRequest.ReqDate = reqDate.Date; // Gets only the date component, discards time
}
else
{
    // Handle parsing failure here (e.g., log an error, set a default date)
}

2. Problem with startDateTime parsing

The error here means your format string "dd/MM/yyyy hh:mm tt" doesn't match the actual format of the startDateTime parameter. Common culprits include:

  • Mixed-up month and day (MM vs dd) if the parameter uses MM/dd/yyyy instead of dd/MM/yyyy
  • The parameter uses 24-hour time (e.g., 00:00:00) instead of 12-hour time with AM/PM (the tt part)
  • Missing seconds (:ss) in your format string that exist in the input

Fix for startDateTime

First, confirm the exact format of your startDateTime parameter. Then use TryParseExact to safely handle valid formats without throwing exceptions:

var reqDateTimeStr = Request.QueryString["startDateTime"];
// Check for 24-hour format first (matches your StartDate example)
if (DateTime.TryParseExact(reqDateTimeStr, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime reqDateTime))
{
    timingRequest.IgnoreEntry = reqDateTime;
}
// Add a fallback for 12-hour format if needed
else if (DateTime.TryParseExact(reqDateTimeStr, "MM/dd/yyyy hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out reqDateTime))
{
    timingRequest.IgnoreEntry = reqDateTime;
}
else
{
    // Handle invalid input (log details, return a user-friendly error, etc.)
}

Key Takeaways

  • Your format string must exactly match the input string—every space, separator, and time component counts
  • Avoid manual string slicing for date handling; parse the full string and extract parts you need
  • Use TryParseExact instead of ParseExact to gracefully handle bad input without crashing your app

内容的提问来源于stack exchange,提问作者user9630128

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:15:02