SharePoint查询日期格式转换问题:转MM/dd/yyyy 12小时制
Hey there! The issue here is that you’re trying to apply date formatting directly to a string value (dateInfo), but String.Format can only use those date-specific format specifiers on actual DateTime objects—not plain strings. Here’s how to fix this:
Step 1: Convert the SharePoint date string to a DateTime object
First, you need to parse the raw date string from SharePoint into a DateTime instance. You can use DateTime.Parse for straightforward cases, or DateTime.TryParse if you want to handle invalid date strings gracefully (to avoid exceptions):
// Option 1: Direct parse (throws exception if the string is invalid) DateTime alteredDate = DateTime.Parse(xNode.Attributes["Altered"].Value); // Option 2: Safer TryParse (no exception, validates the date first) if (DateTime.TryParse(xNode.Attributes["Altered"].Value, out DateTime alteredDate)) { // Proceed with formatting } else { // Handle invalid date case (e.g., append an error message) sb.Append("Invalid date"); }
Step 2: Format the DateTime to your desired 12-hour format
Now that you have a DateTime object, you can format it using the correct specifiers. Based on your request (month/day/year with 12-hour time), use the format string "MM/dd/yyyy h:mm:ss tt"—this will produce something like 04/27/2023 4:27:12 PM.
A quick critical note: MM stands for two-digit months, while mm stands for minutes. Make sure you use MM for the month part (matching your original code’s intent). If you don’t want the AM/PM indicator, omit the tt segment to get 04/27/2023 4:27:12.
Putting it all together, here’s the full working code:
string rawDate = xNode.Attributes["Altered"].Value; if (DateTime.TryParse(rawDate, out DateTime alteredDate)) { // Format with AM/PM (matches your 12-hour requirement) sb.Append(string.Format("{0:MM/dd/yyyy h:mm:ss tt}", alteredDate)); // Or without AM/PM: // sb.Append(string.Format("{0:MM/dd/yyyy h:mm:ss}", alteredDate)); } else { sb.Append("Invalid date value"); }
Why your original code failed
When you pass a string to String.Format with a date specifier like {0:MM/dd/yyyy}, .NET doesn’t recognize it as a date—it treats it as plain text, so the format specifier does nothing. Converting to a DateTime first tells .NET to apply date-specific formatting rules.
That should give you exactly the format you need!
内容的提问来源于stack exchange,提问作者HotTomales

