Hi,
I want to convert the date format from MM/dd/yyyy to yyyy-mm-dd in asp.net MVC. I tried the below two methods.
1) DateTime dt2 = DateTime.Now;
dt2 =DateTime.ParseExact(s, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
2) DateTime dt2 = DateTime.Now;
dt2= DateTime.ParseExact(s, "MM'/'dd'/'yyyy HH:mm:ss", null);
This is working in one server but not working on another server. Please help me to resolve the issue

Prasad RaveendranRank #320 · 7.8K reputationPosted Oct 12, 2023, 7:36 PM EDT
It seems like you're trying to convert a date from the "MM/dd/yyyy" format to the "yyyy-MM-dd" format in an ASP.NET MVC application. The issue you're encountering could be due to differences in the culture settings or date formats on the two servers. Here's a more reliable approach that should work consistently across different servers:
string inputDate = "12/31/2023"; // Replace this with your input date DateTime dt; if (DateTime.TryParseExact(inputDate, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { string formattedDate = dt.ToString("yyyy-MM-dd"); // Now, 'formattedDate' contains the date in yyyy-MM-dd format } else { // Handle parsing error }In this code:
We use
DateTime.TryParseExactto parse the input date using the "MM/dd/yyyy" format. By usingCultureInfo.InvariantCulture, you ensure that the format is consistent, regardless of the server's culture settings.If the parsing is successful, you can then use
ToStringto format theDateTimeobject in the desired "yyyy-MM-dd" format.This approach should be more reliable across different server configurations. Make sure to replace
"12/31/2023"with your actual input date.