Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime Convert from MMM-yyyy to dd-MM-yyyy or yyyy-MM-dd

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?

like image 306
quasar Avatar asked Jan 26 '23 22:01

quasar


2 Answers

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

like image 51
Tim Rutter Avatar answered Feb 02 '23 08:02

Tim Rutter


Use

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

This will give you first of the month anyway.

like image 29
Alok Avatar answered Feb 02 '23 10:02

Alok