-4
string date1="06/06/2017";
string date2="06/05/2017";

The dates are in format mm/dd/yyyy.I need to compare two dates

string test = DateTime.ParseExact(date1, "DD/M/yyyy", CultureInfo.InvariantCulture);

I am unable to find out why I am getting error like String was not recognized as a valid DateTime.

Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44

2 Answers2

4

The dates are in format "mm/dd/yyyy"

If dates are in this format use "MM/dd/yyyy" in ParseExact():

var test = DateTime.ParseExact(date1, "MM/dd/yyyy", CultureInfo.InvariantCulture);

Also, ParseExact() returns DateTime, not string. Use var or DateTime.

Roman
  • 11,966
  • 10
  • 38
  • 47
  • 1
    Important to note that it works only with `InvariantCulture`, otherwise the local date separater is used. – Tim Schmelter Jun 06 '17 at 09:37
  • else if (DateTime.ParseExact(date1, "MM/dd/yyyy", CultureInfo.InvariantCulture).Date < DateTime.ParseExact(date2, "dd/MM/yyyy", CultureInfo.InvariantCulture).Date && chk2.Checked == false) { Page.ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Effective date from cannot be less than Effective To date !!!');", true); return; } Its giving error – priya thapliyal Jun 06 '17 at 09:40
  • @priyathapliyal, you use `"dd/MM/yyyy"` when parse `date2`. Use `"MM/dd/yyyy"` – Roman Jun 06 '17 at 09:42
  • String was not recognized as a valid DateTime – priya thapliyal Jun 06 '17 at 09:50
  • @priyathapliyal, do you use same dates as in question? – Roman Jun 06 '17 at 09:52
1

Use ToString() method like this DateTime.ParseExact(date1,"MM/dd/yyyy",CultureInfo.InvariantCulture).ToString(); this should solve your problem. problem is you cannot implicitly convert DateTime to string.

Mlarnt90
  • 176
  • 1
  • 4
  • 19
  • @priyathapliyal you have to convert the DateTime object to string. DateTime.ParseExact returns DateTime so you have to convert it to string using ToString() – Mlarnt90 Jun 06 '17 at 10:02