0

I'm working on creating my own datetimepicker. I want to show the date as by the dateformat. The dateformat includes "MM-dd-yyyy" and other formats.

I wrote the code as below:

public DateTime getCurrentDate(string dateFormat)
{            
     curDate = DateTime.Now;            
     IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-us", true);
     return DateTime.ParseExact(curDate.ToShortDateString(), dateformat, theCultureInfo); 
}

When I execute the program it shows: String was not recognized as a valid DateTime.

Provide me some solution to handle with error.

Suraj Shrestha
  • 1,790
  • 1
  • 25
  • 51
  • There is a lot of missing data, but this might help: http://stackoverflow.com/questions/2356601/custom-datetime-model-binder-in-asp-net-mvc/8035636#8035636 – gdoron Nov 07 '12 at 08:27
  • i only want to know about: String not recognized as a valid DateTime. how this error occured? – Suraj Shrestha Nov 07 '12 at 08:39

2 Answers2

1

DateTime.ParseExact Method requires the format of the string representation matching the specified format exactly. So DateTime.ParseExact(s,format,provider) expects both s (specified by provider) and format having same format otherwise it throws String not recognized as a valid DateTime

In your case dateFormat has to be

DateTime y = getCurrentDate("dd/MM/yyyy"); //or
DateTime x = getCurrentDate("MM/dd/yyyy");
Kaf
  • 33,101
  • 7
  • 58
  • 78
0

Finally, I got it.. I solve the problem like this..

 public string getCurrentDate(string dateFormat)
 {
     curDate = DateTime.Now.ToShortDateString();
     curDate = String.Format("{0:" + dateFormat + "}", Convert.ToDateTime(curDate));
     return curDate;
 }
Suraj Shrestha
  • 1,790
  • 1
  • 25
  • 51