I'm submitting date value from view in format MMM-yyyy ie "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 (ie 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?
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
Use
DateTime.ParseExact(dt, "MMM-yyyy", CultureInfo.InvariantCulture)
This will give you first of the month anyway.
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);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.