1

I am trying to convert the value of raddatepicker to YYYY-MM-DD format. But I am getting exception,

orderDate.SelectedDate = DateTime.Now.Date;   // Date = {15/7/2015 12:00:00 AM}
string orderDate_ = orderDate.SelectedDate.Value..ToShortDateString();  // 15/7/2015

IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(orderDate_, "yyyy-MM-dd", culture);  // geting exception [System.FormatException] = {"String was not recognized as a valid DateTime."}

Getting exception

[System.FormatException] = {"String was not recognized as a valid DateTime."}

Please suggest how to convert the date format to yyyy-MM-dd.

user4221591
  • 2,084
  • 7
  • 34
  • 68

2 Answers2

0

You have to give the correct format, you need dd-MM-yyyy instead of yyyy-M-dd, you can find more in this article Custom Date and Time Format Strings

DateTime dateVal = DateTime.ParseExact(orderDate_, "dd-M-yyyy", CultureInfo.InvariantCulture); 
Adil
  • 146,340
  • 25
  • 209
  • 204
  • what in case of months greater than 9? I mean for October, November & December – user4221591 Jul 15 '15 at 06:53
  • The format string "M" is for 1-12, it is mentioned in the link I have in my answer, https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx – Adil Jul 15 '15 at 06:56
0

Since orderDate_ looks 15/7/2015, you need to use dd/M/yyyy format instead.

DateTime dateVal = DateTime.ParseExact(orderDate_, "dd/M/yyyy", culture);

But I think this is unnecessary because your orderDate.SelectedDate is already a DateTime.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364