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,745
  • 1
  • 24
  • 50

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
  • 32,033
  • 7
  • 53
  • 77
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,745
  • 1
  • 24
  • 50