DateTime.ParseExact报错:字符串未被识别为有效DateTime求助
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 (
MMvsdd) if the parameter usesMM/dd/yyyyinstead ofdd/MM/yyyy - The parameter uses 24-hour time (e.g.,
00:00:00) instead of 12-hour time with AM/PM (thettpart) - 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
TryParseExactinstead ofParseExactto gracefully handle bad input without crashing your app
内容的提问来源于stack exchange,提问作者user9630128

