convert date format to YYYY-MM-DD of raddatepicker value

4k views Asked by At

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.

2

There are 2 answers

2
Adil On

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); 
2
Soner Gönül On

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.