4
votes

I'm submitting date value from view in format MMM-yyyy i.e. "Apr-2019" as string. I need to get the string value converted into .Net supported date format like dd-MM-yyyy or yyyy-MM-dd. Here dd will be first day of the month.

I've already searched stackoverflow datetime conversion problems, but those all described about three part date conversion problems. If I try to parse the string adding dd part (i.e. 01-Apr-2019), it says- "String was not recognized as a valid DateTime". But if I use numeric value of MMM with that string, then the string is recognizable and I can use ParseExact-

//string dt = "01-Apr-2019";//Not recognizable string format
string dt = "01-04-2019";//Recognizable string format
DateTime newDt = DateTime.ParseExact(dt, "dd-MM-yyyy", CultureInfo.InvariantCulture);

So, is there any built in method/class in .Net which I can use to convert "Apr-2019" format value and achieve my dd-MM-yyyy or yyyy-MM-dd or any other .Net recognizable format?

4
MMM-yyyy will parse "Apr-2019", so it's not clear what your problem is.Jeroen Mostert
I was not aware of "MMM-yyyy" format. Thanks for the point @Jeroen Mostertquasar
I was confused because you mention this very format in your question itself. When in doubt, try it out. :-)Jeroen Mostert

4 Answers

5
votes

Why do you need to convert the string?

Just do parse exact on the format you want:

DateTime newDt = DateTime.ParseExact(dt, "MMM-yyyy", CultureInfo.InvariantCulture);

It will set the day to the first of the month

3
votes

Use

DateTime.ParseExact(dt, "MMM-yyyy", CultureInfo.InvariantCulture)

This will give you first of the month anyway.

0
votes

OP wants to convert the string with the day as well. Use the below code, you can use the format dd-MMM-yyyy.

string dt = "01-Apr-2019";
DateTime newDt = DateTime.ParseExact(dt, "dd-MMM-yyyy", CultureInfo.InvariantCulture);
0
votes

I have tried the below code it was works for me. Could you try this one. string strDt = "Sep-2019"; DateTime dt = Convert.ToDateTime(strDt).AddDays(0.0);