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 RaveendranPosted Oct 12, 2023, 11:36 PM
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:
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.