Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to DateTime and format

Tags:

c#

datetime

Can i convert the string below to DateTime

Friday, 27th September 2013

This is what i want to achieve:

String tmpDate="Friday, 27th September 2013";
closingDate = Convert.ToDateTime(tmpDate).ToString("yyyy-MM-dd");

Doing above i get error:

The string was not recognized as a valid DateTime. There is an unknown word starting at index 10.

like image 230
confusedMind Avatar asked Aug 27 '26 09:08

confusedMind


1 Answers

Well, I'm not sure there is exactly solution with -th, -st, -nd, but you can use this like;

string tmpDate = "Friday, 27 September 2013";
DateTime dt = DateTime.ParseExact(tmpDate,
                                  "dddd, dd MMMM yyyy",
                                  CultureInfo.InvariantCulture);

Here a DEMO.

I almost suggest you remove -th, -st and -nd part of your string but these are break the rules :)

  • August
  • Monday
  • Thursday
  • Sunday

Also check Habib's answer which seems nice.

like image 113
Soner Gönül Avatar answered Aug 28 '26 22:08

Soner Gönül



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!