C# Convert date (day-Month-year) to MM/dd/yyy Error String was not recognized as a valid DateTime

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



C# Convert date (day-Month-year) to MM/dd/yyy Error String was not recognized as a valid DateTime



I am reading a date from a csv which has date in format "8-Mar-18". I am using DateTime.ParseExtract to convert it to date format "MM/dd/yyyy" but I am getting error as



String was not recognized as a valid DateTime.



Here is a repro:


using System.Globalization;

DateTime.ParseExact("8-Mar-18", "MM/dd/yyyy", CultureInfo.InvariantCulture);



How do I convert it to MM/dd/yyy ?



Thanks all.





"8-Mar-18" is not "MM/dd/yyyy" is it? Further. dates do not have a format so this may all be for nought
– Plutonix
24 mins ago






If you want to parse a string into a DateTime use the correct format string. The result will be a DateTime object which does not have any format. It's a binary value
– Panagiotis Kanavos
23 mins ago





DateTime.Parse("8-Mar-18", CultureInfo.InvariantCulture) works just fine. It returns a DateTime object whose value is March 8, 2018. Formatting applies only during parsing or generating strings. If you want to display a DateTime in a certain way use a format string, or the set the appropriate Format property in whatever control or UI element you use to display it
– Panagiotis Kanavos
22 mins ago



DateTime.Parse("8-Mar-18", CultureInfo.InvariantCulture)


Format




2 Answers
2



It's a two step process.


DateTime d = DateTime.ParseExact("8-Mar-18", "d-MMM-yy", CultureInfo.InvariantCulture);
string s = d.ToString("MM/dd/yyyy");





That generates a string, not a DateTime. DateTime has no format. DateTime.Parse("8-Mar-18", CultureInfo.InvariantCulture) would work just as well, there's no reason to use ParseExact
– Panagiotis Kanavos
20 mins ago



DateTime.Parse("8-Mar-18", CultureInfo.InvariantCulture)


ParseExact





@PanagiotisKanavos thanks for the details.
– ProgSky
18 mins ago



It can be done on one line.


var s = DateTime.ParseExact("8-Mar-18", "d-MMM-yy", CultureInfo.InvariantCulture).ToString("MM/dd/yyyy");






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard